rust持续学习 get_or_insert_with

通常使用一个值

if(x===null)x=some_valid_value

忽然今天看见一段代码

rust 复制代码
pub fn get_id() -> u64 
{
let mut res = struct.data.borrow_mut();
*res.get_or_insert_with(||{
 let mut xx = ...... some logic
 let id = xx.id; 
 id});
}

感觉这个名字蛮奇怪的 insert

然后翻了一下代码,是来自option.rs,原来就是空则赋值,这个写法对我来说蛮新奇的

rust 复制代码
    #[inline]
    #[stable(feature = "option_entry", since = "1.20.0")]
    #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
    pub const fn get_or_insert_with<F>(&mut self, f: F) -> &mut T
    where
        F: ~const FnOnce() -> T,
        F: ~const Destruct,
    {
        if let None = *self {
            // the compiler isn't smart enough to know that we are not dropping a `T`
            // here and wants us to ensure `T` can be dropped at compile time.
            mem::forget(mem::replace(self, Some(f())))
        }

        // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
        // variant in the code above.
        unsafe { self.as_mut().unwrap_unchecked() }
    }
相关推荐
qq_448011166 分钟前
C语言中的getchar()
c语言·开发语言
肖志-AI全栈11 分钟前
JavaScript 快速排序:从 pivot、双指针到分治思想
开发语言·javascript·排序算法
野生风长28 分钟前
c++类和对象(this指针,重载operator,习题总结)
java·开发语言·c++
雪的季节36 分钟前
Python「假多态」与 C++「真多态」的核心区别
开发语言·c++
筱谙40 分钟前
BES BLE CTKD 完整学习笔记
笔记·学习
皓月斯语1 小时前
程序设计语言的特点
开发语言·数据结构·c++
程序员爱钓鱼1 小时前
Rust Vec 动态数组详解:创建、增删、遍历与排序
前端·后端·rust
超人不会飞_Jay1 小时前
Go课程2
开发语言·后端·golang
minglie11 小时前
zynq开发板的xvcServer作为烧录器
学习
_abab1 小时前
Rust重塑系统编程:从Linux内核到AI推理引擎的2026全景解析
linux·人工智能·rust