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() }
    }
相关推荐
阿俊-全栈开发1 小时前
LikeShop 单商户SaaS商城分销模块二开:佣金计算与结算逻辑实现
java·开发语言·微服务·likeshop·likeshop开源商城·likeshop多商户
GEO从入门到精通3 小时前
课程怎么选?2026年GEO学习资源全梳理
学习
优化Henry4 小时前
LTE 载波频率与频点配置详解
运维·网络·学习·5g·信息与通信
m0_380743874 小时前
C++中的freopen的用法实例详解
开发语言·c++
xiaomu001234 小时前
高湿环境床垫湿度管理技术框架:湿度阈值、排湿结构与材料选型
经验分享·学习·学习方法
Escalating_xu5 小时前
【Python】基础语法(1):常量、变量、类型、输入输出与运算符
开发语言·python
zhangrelay5 小时前
ROS项目设计案例智能大模型正经乱答案例
linux·笔记·学习·ubuntu·机器人
probex_5 小时前
学习笔记:知识图谱是什么,在测试里能干什么
笔记·学习·知识图谱
jimy15 小时前
polymorph.cpp里面的“析构函数、智能指针”问题
开发语言·c++
m0_380743875 小时前
PHP 8.3 缓存清除不生效怎么排查
开发语言·php