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() }
    }
相关推荐
西西弗Sisyphus5 小时前
Qt 无边框窗口自己实现拖拽与缩放
开发语言·qt
对象存储与RustFS5 小时前
给 RustFS 拆多租户权限:IAM 用户、组与策略的实战
后端·rust·开源
狮子雨恋5 小时前
anaconda python环境和QT python环境不一致如何解决
开发语言·python·qt
旖旎夜光5 小时前
【AI入门】大模型介绍全解析:从模型、LLM 到提示词与嵌入
人工智能·笔记·python·学习·ai编程
独立开发之道5 小时前
【three.js教程】Three.js 矩阵变换:position/quaternion/scale 和 matrix 到底怎么配合
开发语言·javascript·矩阵
纪念 2295 小时前
数据结构排序(四)
开发语言·数据结构
IvanCodes5 小时前
Python 基础语法(四):循环结构与流程控制
开发语言·python
OPEN-F5 小时前
C++工程化:编译链接、调试与性能优化
开发语言·c++
xxwl5855 小时前
Git常用命令的学习
git·学习
具身AGI5 小时前
从演示到作业,物理AI 人类学习路线 的深意
人工智能·学习