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() }
    }
相关推荐
Boom_Shu几秒前
浅拷贝与深拷贝
开发语言·c++·算法
hhcgchpspk6 分钟前
xss漏洞学习笔记
笔记·学习·网络安全·xss
2601_961845157 分钟前
2026法考资料pdf|电子版|资料已整理
开发语言·前端框架·pdf·c#·xhtml·csrf·view design
何以解忧,唯有..7 分钟前
Go 语言数据类型详解:从基础到复合类型
开发语言·golang·mfc
Mortalbreeze10 分钟前
C++ Lambda表达式详解:从捕获列表到底层原理
开发语言·c++
情绪总是阴雨天~13 分钟前
OCR光学字符识别技术:完整原理与实战学习笔记
笔记·学习·ocr
MATLAB代码顾问16 分钟前
Python NumPy数值计算核心指南
开发语言·python·numpy
searchforAI17 分钟前
B站视频怎么转文字稿?AI自动总结要点+生成思维导图教程
人工智能·笔记·学习·ai·语音识别·知识管理·视频总结
只做人间不老仙21 分钟前
C++ grpc 拦截器示例学习
开发语言·c++·学习
踏着七彩祥云的小丑22 分钟前
Go学习第7天:Map集合 + 递归函数 + 类型转换
开发语言·学习·golang·go