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() }
    }
相关推荐
geovindu8 分钟前
python: Decision Tree
开发语言·后端·python·决策树
穗余32 分钟前
以太坊面试深度:transfer vs send vs call.value 机制与 2300 Gas 限制
rust·solidity面试·eip-1884·eip-2929·returnbomb
时间的情敌1 小时前
Three.js 工业场景性能优化合集|大批量管线、InstancedMesh 实例化、合并 Geometry、显存释放
开发语言·javascript·性能优化·three.js
源码手记1 小时前
基于微信小程序的驾考刷题学习系统-毕设源码
学习·微信小程序·课程设计
小李不想当小白1 小时前
HAL库之定时器输出比较(STM32 HAL库学习笔记)
笔记·stm32·单片机·嵌入式硬件·学习·嵌入式
步峰代理-盾山2 小时前
R语言爬虫实战:使用httr与XML解析网页数据并进行统计分析
xml·开发语言·爬虫·r语言·网络爬虫
Kapaseker3 小时前
百炼成金!Rust 1.100.0 正式发布
rust
sharemylove12 小时前
Java集合框架全面详解
java·开发语言·经验分享·笔记·学习
郝学胜-神的一滴16 小时前
Effective Python 条款43:自定义容器类
开发语言·windows·python·pandas·scikit-learn·pyqt
好焊孙辉17 小时前
一条产线省下 30 个电机位:Z 轴和 R 轴,该合成一个了
开发语言·r语言