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() }
    }
相关推荐
海兰13 小时前
【 Python 量化交易】第3章:金融基础概念
开发语言·python·金融
一木 之林13 小时前
三.C++ 内存管理(进阶)(二)
开发语言·arm开发·c++
吴声子夜歌13 小时前
Java——类、对象及方法(一)
java·开发语言
阿里嘎多学长13 小时前
2026-08-29 GitHub 热点项目精选
开发语言·程序员·github·代码托管
凯尔萨厮14 小时前
Java学习笔记十(注解)
java·笔记·学习
JoannaJuanCV14 小时前
VLM学习-SFT(监督微调)
深度学习·学习·机器学习·大模型·视觉大模型·vlm·视觉编码器
এ慕ོ冬℘゜14 小时前
JavaScript学习心得:从只会语法,到真正会写业务逻辑
开发语言·javascript·ecmascript
2601_9669496514 小时前
五档盘口数据对量化交易有什么价值?从信号判断到策略风险的完整分析
开发语言·人工智能·python·数据分析·量化·股票数据·quantdash
小吴学不废Java14 小时前
Python 基础语法
开发语言·python
布莱克60515 小时前
队列详解:定义、分类、应用场景及与栈的区别(C/C++ 代码讲解)
c语言·开发语言·c++·队列