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() }
    }
相关推荐
Ai-_Man8 分钟前
ChatGPT还是不可以导出左侧所有对话,只能点进去单条内容导出,方法不对吗?
开发语言·javascript·人工智能·chatgpt·小程序·ecmascript
问天_观心12 分钟前
模型微调学习(二)
开发语言·人工智能·学习·语言模型·github
小羊没烦恼!13 分钟前
深入浅出SQL Server中的死锁
java·开发语言·前端·数据库·后端·spring·c#
白露与泡影13 分钟前
Java 面试八股文及答案整理 | 后端面试高频题(2026)
java·开发语言·面试
夜晚回家19 分钟前
Python 赋值运算符详解 | 从 = 到 +=,一张记账单讲清复合赋值
开发语言·python
dadaobusi20 分钟前
学习:PCIe6.0 RS FEC
学习
_橙时_21 分钟前
【MOEA/D的学习小笔记】
笔记·学习·多目标优化·moea/d
kaixin_learn_qt_ing25 分钟前
QCommandLineParser 学习
学习
布莱克60527 分钟前
QtWidgets 与 QML:两大 UI 开发框架的全面对比
开发语言·c++·qt·ui·架构
张伯毅38 分钟前
External Shuffle Service(spark3_shuffle):原理、配置与排障
java·开发语言·spark·yarn