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() }
    }
相关推荐
心中有国也有家16 分钟前
AtomGit Flutter 鸿蒙客户端: ChangeNotifier 模式
学习·flutter·华为·harmonyos
luj_176826 分钟前
心形曲线轨迹控制三大关键技术
c语言·开发语言·c++·经验分享·算法
取地址符36 分钟前
C++学习笔记(基于learn-cxx)(1)
c++·经验分享·笔记·学习
Mininglamp_27181 小时前
Claude Code 封禁中国开发者之后:本地 AI 编程工具的替代方案实测
开发语言·人工智能·windows·开源软件·ai-native
思麟呀1 小时前
C++17(三)if constexpr+折叠表达式
开发语言·c++
醉城夜风~1 小时前
Java详解经典算法题:接雨水(三种实现方案+原理剖析)
java·开发语言·算法
明理的信封1 小时前
AI 基础设施的“去 Python 化“:Rust 与 C# 的两条替代路径
人工智能·python·rust
qydz111 小时前
杰理开发基础知识(3)
开发语言·嵌入式开发·杰理科技
贾斯汀frank1 小时前
C# 15 类型系统改进:Union Types
开发语言·windows·c#
阿里嘎多学长2 小时前
2026-07-10 GitHub 热点项目精选
开发语言·程序员·github·代码托管