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() }
    }
相关推荐
娇娇yyyyyy35 分钟前
Qt编程(3): 信号和槽函数
开发语言·数据库·qt
wwww.wwww40 分钟前
qt程序执行时报错:无法定位程序输入点,但是通过IDE的run又可以正常的运行。
开发语言·ide·qt
好奇龙猫3 小时前
【日语学习-日语知识点小记-日本語体系構造-JLPT-N2前期阶段-第一阶段(19):単語文法】
学习
乌鸦乌鸦你的小虎牙4 小时前
qt 5.12.8 配置报错(交叉编译环境)
开发语言·数据库·qt
feifeigo1234 小时前
Leslie人口模型MATLAB实现(中长期人口预测)
开发语言·matlab
写代码的二次猿4 小时前
安装openfold(顺利解决版)
开发语言·python·深度学习
一只大袋鼠4 小时前
Redis 安装+基于短信验证码登录功能的完整实现
java·开发语言·数据库·redis·缓存·学习笔记
※DX3906※5 小时前
Java排序算法--全面详解面试中涉及的排序
java·开发语言·数据结构·面试·排序算法
笨笨马甲6 小时前
Qt QSS使用指南
开发语言·qt
Nan_Shu_6147 小时前
学习: 尚硅谷Java项目之小谷充电宝(3)
java·后端·学习