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() }
    }
相关推荐
今夜有雨.4 分钟前
C# 学习文档(零基础入门)
开发语言·学习·c#
软件黑马王子42 分钟前
14.事件中心:主要作用和原理
开发语言·前端框架·c#
君顾11 小时前
酒吧点餐小程序系统开发实战:从架构设计到上线全流程指南
java·开发语言·酒吧
lifallen1 小时前
短暂 Agent 与持久化工程:让理解脱离对话
人工智能·学习·ai·重构·ai编程
知识分享小能手1 小时前
深度学习学习教程,从入门到精通,深度模型中的优化 — 完整知识点与代码案例(8)
人工智能·深度学习·学习
似水এ᭄往昔1 小时前
【Qt】--常用控件(显示类控件)
开发语言·qt
互联网叫兽1 小时前
redis深入学习二
数据库·redis·学习
PHP实战开发录2 小时前
PHP文件上传成功为什么页面却找不到
开发语言·nginx·php·开发
是隼人2 小时前
buuctf-pwn mrctf2020_easy_equation(64位fmt)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门