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() }
    }
相关推荐
测试人社区—667920 分钟前
破茧成蝶:DevOps流水线测试环节的效能跃迁之路
运维·人工智能·学习·flutter·ui·自动化·devops
Jackyzhe20 分钟前
Flink学习笔记:多流 Join
笔记·学习·flink
盐焗西兰花3 小时前
鸿蒙学习实战之路 - 网络重连最佳实践
网络·学习·harmonyos
fish_xk4 小时前
c++中的引用和数组
开发语言·c++
酒尘&7 小时前
JS数组不止Array!索引集合类全面解析
开发语言·前端·javascript·学习·js
冬夜戏雪8 小时前
【java学习日记】【2025.12.7】【7/60】
java·开发语言·学习
xwill*8 小时前
分词器(Tokenizer)-sentencepiece(把训练语料中的字符自动组合成一个最优的子词(subword)集合。)
开发语言·pytorch·python
wubba lubba dub dub7508 小时前
第二十八周 学习周报
学习
咖啡の猫8 小时前
Python列表的查询操作
开发语言·python
思成不止于此8 小时前
MySQL 查询实战(三):排序与综合练习
数据库·笔记·学习·mysql