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() }
    }
相关推荐
计算机安禾11 分钟前
【c++面向对象编程】第25篇:仿函数(函数对象):重载operator()
开发语言·c++·算法
Rust语言中文社区11 分钟前
【Rust日报】2026-05-14 Pyrefly v1.0 正式发布:快速的 Python 类型检查器和语言服务器
开发语言·后端·python·rust
kkeeper~31 分钟前
0基础C语言积跬步之深入理解指针(4)
c语言·开发语言
周末也要写八哥1 小时前
在C++中使用预定义宏
开发语言·c++·算法
Data_Journal1 小时前
使用Python lxml轻松进行网络爬取
开发语言·php
李白不吃坚果1 小时前
沟道电荷的思考
学习·cmos·集成电路·模拟集成电路设计·沟道电荷
xcLeigh1 小时前
IoTDB JDBC 完整使用教程:连接、查询、批处理与字符集配置
开发语言·数据库·qt·iotdb·查询·批处理·连接
学会870上岸华师1 小时前
C 语言程序设计——第一章课后编程题
c语言·开发语言·学习·算法
小小编程路1 小时前
新手快速学 Python 极简速成指南
开发语言·c++·python
nashane1 小时前
HarmonyOS 6学习:AI攻略长截图“防抖”与像素级拼接术
学习·华为·harmonyos