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 分钟前
2023_Kirillov_SAM_总结
笔记·学习·遥感
外收内放17 分钟前
Python与AI应用(文件操作)
python·学习
M78佐菲1 小时前
ARM学习笔记(五)
linux·arm开发·笔记·嵌入式硬件·学习
逆向编程1 小时前
QGIS地图投影(CRS坐标参照系)设置
开发语言
free-elcmacom1 小时前
发际线警告!手撕《C陷阱与缺陷》终极 BOSS:signal 函数与 typedef 魔法
c语言·开发语言·visual studio code·visual studio
程序员阿鹏1 小时前
简单介绍一下软引用
java·开发语言·jvm·数据结构·后端
0566462 小时前
用大模型构建答疑机器人:从 API 调用到上下文工程
python·学习·agent
我爱cope2 小时前
【操作系统 | 开篇:什么是操作系统?从裸机到多任务系统】
学习·操作系统
Amos_Web2 小时前
Rspack 源码解析(十一):资产 Hook 与增量构建
前端·rust·源码阅读
haluhalu.2 小时前
初识 Protobuf:微服务跨语言通信的一份契约
java·c语言·开发语言·c++·python