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 分钟前
Java工程师高频面试题(基于近一年的真实面试记录整理)
java·开发语言·面试·预见猿份·老苗项目实战
sunoo-2297 分钟前
51单片机学习Day2:数码管动态扫描、定时器与中断系统深度总
单片机·嵌入式硬件·学习·51单片机
宣宣猪的小花园.11 分钟前
【机器学习】从机理建模到数据学习:机器学习究竟替代了什么
人工智能·学习·机器学习
小小、码农13 分钟前
C++11右值引用与移动语义 —— 从拷贝资源到转移资源
开发语言·网络·c++·网络协议
上海心泾国际物流有限公司21 分钟前
我在几个医疗器械仓库记下的一组温湿度数据
经验分享·笔记·学习·健康医疗·交通物流
for_ever_love__34 分钟前
python基础语法学习: requirements.txt
开发语言·python·学习
XiaoYu1__44 分钟前
JavaGUI文件管理系统开发实战:从静态展示到动态交互的演进
java·开发语言
for_ever_love__1 小时前
python基础语法学习: 动态类型
开发语言·python·学习
霸道流氓气质1 小时前
MCP(Model Context Protocol)核心概念与Java SDK集成
java·开发语言
企查查数据服务1 小时前
全军禁入下客商准入风控,关联图谱与穿透核查
大数据·开发语言·数据库·php