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() }
    }
相关推荐
豆瓣鸡7 分钟前
Gradle学习
学习
海绵宝宝的月光宝盒16 分钟前
2-非金属材料
经验分享·笔记·学习·其他·职场和发展·课程设计·制造
AI首席情报员_阿布28 分钟前
Numa:用 Rust 从零造一个 DNS 解析器,顺手解决了开发者最头疼的几件事
人工智能·rust·dns
|_⊙30 分钟前
C++ 智能指针
开发语言·c++
电子科技圈33 分钟前
IAR作为Qt Group独立BU携两项重磅汽车电子应用开发方案首秀北京车展
开发语言·人工智能·汽车·软件工程·软件构建·代码规范·设计规范
代码中介商34 分钟前
C语言指针深度解析:从数组指针到函数指针
c语言·开发语言
Jasmine_llq1 小时前
《B4356 [GESP202506 二级] 数三角形》
开发语言·c++·双重循环枚举算法·顺序输入输出算法·去重枚举算法·整除判断算法·计数统计算法
止语Lab1 小时前
Go vs Java GC:同一场延迟战争的两条路
java·开发语言·golang
Rust研习社1 小时前
Rust 多线程从入门到实战
开发语言·后端·rust
小饕1 小时前
RAG学习之- RAG 数据导入完整指南
人工智能·python·学习