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() }
    }
相关推荐
小弥儿22 分钟前
GitHub今日热榜 | 2026-08-14:OSINT情报工具回流,本地AI赛道升温
人工智能·学习·开源·github
乐观勇敢坚强的老彭24 分钟前
C++ 竞赛常用算法模板速查表
开发语言·c++·算法
离陌在学C#38 分钟前
C# 泛型:从基础到高级应用
开发语言·c#
ly768939 分钟前
Java 设计模式详解:从原则到 23 种经典模式
java·开发语言·设计模式
小黄人软件41 分钟前
【证书批量转换】PEM->CER证书批量转换工具.exe 纯 Python实现,无需安装OpenSSL
人工智能·学习
SomeB1oody41 分钟前
【RustyML入门】2.13. 孤立森林
开发语言·后端·机器学习·rust·教程
萧瑟余晖1 小时前
Java深入解析篇三十之Java日志框架
java·开发语言
Herbert_hwt1 小时前
【C语言基础】常量、选择结构与运算符全解析
c语言·开发语言·算法
AI视觉网奇1 小时前
动作识别 视频理解大模型
开发语言·python·音视频
DLYSB_2 小时前
Kafka 消费倾斜死锁与 Partition 掉队:我用 Rust 写了个“数据管道物理哨兵”,比 Grafana 报警快了 18 秒
rust·kafka·grafana·报警灯