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() }
    }
相关推荐
少控科技6 分钟前
QT新手日记 030
开发语言·qt
航Hang*14 分钟前
计算机等级考试(二级WPS)---第1章:综合应用基础---第3节:云办公云服务
笔记·学习·wps·复习·计算机二级·计算机等级考试
小此方21 分钟前
Re:从零开始的 C++ STL篇(三)string的疑难问题详细解析:深拷贝,写时拷贝,三个swap
开发语言·c++
荒诞硬汉22 分钟前
抽象相关学习
java·学习
Linux猿27 分钟前
基于Python的图书管理系统(可执行源码+详细报告+详细注释+运行步骤)
开发语言·python·毕业设计·课程设计·管理系统·图书管理系统项目
lanbing28 分钟前
在Mac OS系统中安装Go语言环境教程
开发语言·后端·golang
sensen_kiss32 分钟前
Python安装与环境配置全程详细教学(包含Windows版和Mac版)
开发语言·python·pycharm
程序员敲代码吗33 分钟前
嵌入式C++开发注意事项
开发语言·c++·算法
Dr.Kun36 分钟前
【鲲码园Python】基于yolov11的番茄成熟度检测系统
开发语言·python·yolo
白开水+37 分钟前
AI学习-第二天
python·学习