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() }
    }
相关推荐
布莱克6051 小时前
Swift 循环与控制转移详解:从 for-in 到标签跳转
开发语言·ssh·swift·循环
瑞克-桑切斯2 小时前
Kubernetes 1.28 保姆级新手学习教程
运维·学习·docker·云原生·容器·kubernetes
敲上瘾2 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
联犀2 小时前
ai时代复杂项目的golang项目如何更好的与ai共舞:monorepo+gozero
开发语言·人工智能·golang
SomeOtherTime3 小时前
第 11 讲(大结局):编译期元编程与零拷贝架构——卫生声明宏(macro_rules!)、过程宏 AST 手术刀与 Serde 零反射序列化的终极合龙
rust
lcj25115 小时前
[C++] C++11
开发语言·c++·笔记
kaixin_啊啊5 小时前
【三种鲑科鱼类比较基因组学分析鉴定出参与细胞内寄生菌鲑立克次体抗性的功能候选基因】论文学习
学习
Evand J6 小时前
【MATLAB例程】基于IMM-CKF的AOA+测距融合的二维移动目标跟踪定位
开发语言·matlab·目标跟踪
CappuccinoRose7 小时前
Redis 学习文档
redis·后端·学习·缓存·session·非关系型数据库·gossip
JianZhen✓7 小时前
IM 聊天列表为什么总“消息乱跳“:有序插入、时间轴派生、本地截断、已读回执
开发语言·前端·php