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() }
    }
相关推荐
敲上瘾41 分钟前
Qt 主窗口QMainWindow:菜单栏、工具栏、状态栏与浮动窗口等
开发语言·c++·qt·ui·qt6.3
Century_Dragon1 小时前
把规范练在实操之前——智能网联汽车传感器测试装调教学软件
学习
kyrie_sakura5 小时前
大模型学习27 -- 模型原理1 -- 发展历程
学习
BK贝壳5 小时前
布尔数组也能做按位取反、移位和乘法:bool-hybrid-array 的位运算在本机跑了一遍
开发语言·数据结构·python·性能优化·numpy
吴名氏.6 小时前
全栈跃迁:Java 后端 27 讲【3】Vue3工程化脚手架
java·开发语言·springboot·全栈工程师
codeejun6 小时前
每日一Go·MySQL-24、死锁排查与解决方案
开发语言·mysql·golang
mex_wayne6 小时前
LeRobot SO-ARM101 学习笔记(6) pi0.5--论文阅读
论文阅读·笔记·学习·pi0.5
小此方8 小时前
QT从入门到精通(一)Qt新手保姆级教程:从官网安装到项目实战,四步带你彻底搞懂Qt框架
开发语言·qt
孟陬9 小时前
Foobar 技术周刊#2:约会已死?用户急剧下滑,约会App大概率会弱化约会属性转向轻陪伴。我有个建议:
前端·后端·rust
kaixin_啊啊9 小时前
【DNA数据学习】从DNA序列到模型预测
学习·生物信息