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() }
    }
相关推荐
江苏世纪龙科技17 分钟前
开启汽车实训新视界:大众迈腾整车检测与诊断MR仿真实训系统
学习
好奇龙猫1 小时前
【AI学习-lora-定义-comfyUI相关-相关学习-了解概念(1)】
人工智能·学习
纵有疾風起1 小时前
C++——多态
开发语言·c++·经验分享·面试·开源
冯诺依曼的锦鲤1 小时前
算法练习:差分
c++·学习·算法
氵文大师2 小时前
A机通过 python -m http.server 下载B机的文件
linux·开发语言·python·http
封奚泽优2 小时前
下降算法(Python实现)
开发语言·python·算法
im_AMBER2 小时前
算法笔记 16 二分搜索算法
c++·笔记·学习·算法
赵文宇(温玉)2 小时前
不翻墙,基于Rancher极速启动Kubernetes,配置SSO登录,在线环境开放学习体验
学习·kubernetes·rancher
笃行客从不躺平3 小时前
遇到大SQL怎么处理
java·开发语言·数据库·sql
郝学胜-神的一滴3 小时前
Python中常见的内置类型
开发语言·python·程序人生·个人开发