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() }
    }
相关推荐
狂云歌10 分钟前
AI时代,学什么,怎么学
人工智能·学习
牛油果子哥q14 分钟前
C++序列式容器深度精讲:vector/list/deque底层实现、扩容原理、迭代器失效、性能对比、工程选型避坑
开发语言·c++·list
lingguangbuzhi15 分钟前
【JAVA教程】java课程java学习编程
java·学习·教程
YM52e21 分钟前
鸿蒙 ArkTS 实战|防渣万能执行方案:五阶段防御体系 + 红线清单的代码实现
学习·华为·harmonyos
渡我白衣27 分钟前
Acceptor模块的设计与实现
java·linux·服务器·开发语言·网络·c++·人工智能
优化Henry38 分钟前
关于“星链”互联网系统的几点认识
运维·服务器·网络·笔记·学习·信息与通信
沫璃染墨40 分钟前
《从零入门Linux系统篇(二十八):文件篇·一——Linux为什么“万物皆文件”:从C语言文件流到系统调用》
linux·运维·服务器·开发语言·c++·文件
MartinYeung52 小时前
[论文学习]Poser:通过操纵内部结构揭示对齐伪装的大语言模型
人工智能·学习·语言模型
luteres2 小时前
Mybatis+SSM整合笔记
java·开发语言·mybatis
郝学胜-神的一滴2 小时前
《C++11 工程级应用01:告别冗长类型,开启简洁高效编码新时代》深度解读
开发语言·c++·算法·软件开发·系统设计