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() }
    }
相关推荐
传奇开心果编程12 小时前
【ArkUI 练中学】第14课:应用性能优化实战
学习·ui·华为·harmonyos
事已至此先睡覺吧13 小时前
第三篇:Java 流程控制详解:条件判断、循环与跳转语句
java·开发语言
m0_7345717613 小时前
深入理解5g <二十> dmrs
开发语言·5g
PNP Robotics13 小时前
【PNP具身解读】GPT6 Astra:具身智能新范式,大模型 + Franka机器人快速落地验证一、GPT6 Astra 背后的布局、数据与具身方向
人工智能·学习·机器学习·机器人
小李不想当小白14 小时前
PCB结构与组成(PCB设计入门学习笔记)
经验分享·笔记·单片机·嵌入式硬件·学习·pcb工艺·pcb
那年窗外下的雪.14 小时前
第 02 天:Linux 权限、inode、目录项与链接
学习·http
金金计较.14 小时前
Go语言-4
开发语言·golang
XGStudio202414 小时前
免费安全的 - 二维码转换工具
学习·ai
邵奈一14 小时前
【紧急处理ZCode事件】ZCode 工作区快照静默上传:检测方法与三层防护实践
人工智能·学习·大模型·国产
泡海椒14 小时前
jquick-pdf 表格行列尺寸控制实战:单元格合并的可行边界
java·开发语言·pdf