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() }
    }
相关推荐
ch.ju13 小时前
Java程序设计(第3版)第四章——重载和覆盖的区别
java·开发语言
AOwhisky13 小时前
学习自测与解析:Redis系列第一期与第二期核心知识点详解
运维·数据库·redis·学习·云计算
AI科技星13 小时前
第四卷:橡皮泥江湖(拓扑学)
c语言·开发语言·网络·量子计算·agi·拓扑学
浮尘笔记13 小时前
Go实现大文件异步流式采集引擎
开发语言·后端·golang
zhangrelay13 小时前
个体智能大模型使用的主观数据复盘-节选-2026-
笔记·学习·课程设计
yugi98783813 小时前
基于C#实现数字识别率的OCR方案
开发语言·c#·ocr
星越华夏13 小时前
python中四种获取文件后缀名的方法
开发语言·python
lunzi_082613 小时前
【学习笔记】《Python编程 从入门到实践》第9章:类、继承、组合与面向对象编程
笔记·python·学习
aXin_ya13 小时前
Ai Vibecoding学习(Claude Code的安装使用前置)
学习·vibe codeing
Fuly102413 小时前
LangGraph学习-(3)人工审批
学习