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() }
    }
相关推荐
释厄6231 分钟前
智能体释放度子集律——文本 ⊂ 音频 ⊂ 视频⊂ 游戏
开发语言·游戏·microsoft·音视频
星恒随风11 分钟前
Linux基础IO万字详解:从文件描述符fd到重定向、FILE缓冲机制及MiniShell升级
linux·运维·笔记·学习·状态模式
对象存储与RustFS15 分钟前
JuiceFS + 对象存储:把 S3 变成 POSIX 文件系统实测
后端·rust·开源
Sarvartha20 分钟前
Object 类
java·开发语言
小雪崩28 分钟前
嵌入式学习 day65:Linux驱动进阶——pinctrl 子系统和 platform 驱动框架
linux·学习·驱动
shixiexunnie32 分钟前
Raw NAND 驱动库学习
驱动开发·学习
j7~35 分钟前
【C++ 标准项目】发布订阅消息队列 (篇七):项目创建与基础工具模块搭建
开发语言·c++·log4j·uuid·protobuf·helper工具·消息定义类型和交换机类型定义
leisoo809738 分钟前
股票筹码分布怎么用获利比例成本区间与集中度实战 IG50免费开源股票数据API接口
开发语言·jvm·数据库·python·开源
喜欢打篮球的普通人1 小时前
MiniMind 学习笔记(二十二):数学 Cookbook——把概率空间、期望、似然一次讲明白
人工智能·笔记·学习
Lazionr1 小时前
unordered_map和unordered_set的使用
开发语言·c++·算法