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() }
    }
相关推荐
Wang's Blog4 分钟前
Java 项目实战: 外卖平台优化-YApi接口管理平台与文档导入导出
java·开发语言·yapi
jimy111 分钟前
基类没有虚析构函数,基类指针删除派生类对象,行为是未定义的
开发语言·c++
迅猛龙办公室20 分钟前
python获取星期字符串
开发语言·python
小黄蚁21 分钟前
使用LVGL模拟示波器创建正弦函数波形
单片机·学习
辣知37 分钟前
辣知·化智71 四川广汉三星堆的金铜贝
学习
天天进步201544 分钟前
90天AI接单学习路线:从LLM应用到AI Agent
人工智能·学习
vx_Biye_Design1 小时前
springboot小学生英语学习APP62773-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·学习·课程设计
@Mike@1 小时前
13-数据库学习笔记(查询执行处理模型)
数据库·笔记·学习
泡海椒1 小时前
JQuick-Excel dateFormat 转换实战:日期值与 FORMAT 显示格式的边界
开发语言·python·excel
白杨尚青2 小时前
C++入门篇(十三):vector(上)——动态数组:构造、空间增长与迭代器失效
开发语言·c++·笔记·算法·stl