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() }
    }
相关推荐
一只小菜鸡..9 小时前
南京大学 操作系统 (JYY) 学习笔记:进程、系统调用与状态机管理
笔记·学习
互联网中的一颗神经元9 小时前
小白python入门 - 39. 采集流水线小项目
开发语言·python
Wang's Blog9 小时前
Go-Zero 项目开发22:用户群聊功能的实现与完善
开发语言·golang
a11177610 小时前
坦克大战3D Three.js 3D (开源项目)
开发语言·javascript·3d
Ivanqhz11 小时前
Rust &‘static str浅析
java·前端·javascript·rust
Wang's Blog11 小时前
Go-Zero项目开发24: 基于Bitmap实现群聊消息已读未读
开发语言·后端·golang
天国梦12 小时前
2026英语教学系统选型实战:AI如何让备课效率提升42%?天学网技术落地全解析
人工智能·学习
维克兜率天12 小时前
【维克】大数定律与中心极限定理:为什么长期均值终将回归?
经验分享·学习·金融·概率论
中微极客13 小时前
降维算法75倍加速:从PCA到稀疏字典学习的工程实践
人工智能·学习·算法
吃好睡好便好14 小时前
MATLAB中图像的读取、写入和显示
开发语言·图像处理·学习·计算机视觉·matlab