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() }
    }
相关推荐
孬甭_2 小时前
C++ string类
开发语言·c++
Python图像识别-12 小时前
基于yolov8的钢铁缺陷检测系统-2027毕业版(UI界面+Python项目源码+模型+标注好的数据集)
开发语言·python·yolo
sycmancia2 小时前
Qt——多线程与界面组件的通信
开发语言·qt·算法
你驴我2 小时前
WhatsApp 多账号消息路由中的去重与顺序保证实践
开发语言·php
万岳科技系统开发2 小时前
智慧医院小程序开发满足医疗机构多场景服务需求
数据库·学习·小程序
笑鸿的学习笔记3 小时前
C++笔记之内存映射、零拷贝与共享内存(学习三)-操作系统术语概念图
笔记·学习
wordpress资料库3 小时前
Next.js更适合移动开发 不适合web开发
开发语言·前端·javascript·next.js
wujf903 小时前
Go 内存泄漏排查完整教程 (pprof)
开发语言·golang·xcode
既然如此,那就开摆3 小时前
ULIP总结
笔记·学习