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() }
    }
相关推荐
辞旧 lekkk1 分钟前
【c++】c++11(上)
开发语言·c++·学习·萌新
程序员阿鹏3 分钟前
SpringBoot自动装配原理
java·开发语言·spring boot·后端·spring·tomcat·maven
彭世瑜6 分钟前
C/C++:libfort用于在终端输出表格
c语言·开发语言·c++
RAY_01047 分钟前
Python—数据可视化pyecharts
开发语言·python
徐同保7 分钟前
n8n+GPT-4o一次解析多张图片
开发语言·前端·javascript
春日见11 分钟前
如何跑通,吃透一个开源项目?
linux·运维·开发语言·数码相机·matlab
技术净胜16 分钟前
MATLAB数据清洗流程包含:缺失值处理/异常值检测/重复值删除
开发语言·matlab
SmoothSailingT17 分钟前
C#——textBox控件(1)
开发语言·c#
走在路上的菜鸟23 分钟前
Android学Dart学习笔记第二十一节 类-点的简写
android·笔记·学习·flutter
黑客思维者25 分钟前
机器学习009:监督学习【回归算法】(岭回归)-- 给模型一个“清醒”的约束
学习·机器学习·回归·监督学习·岭回归