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() }
    }
相关推荐
电商API_1800790524717 分钟前
淘宝评论API技术解析与调用实战指南
开发语言·爬虫·信息可视化
百***074518 分钟前
gpt-image-1.5国内API稳定接入全方案(含多模态实操)
开发语言·gpt·php
代码游侠18 分钟前
应用——MPlayer 媒体播放器系统代码详解
linux·运维·笔记·学习·算法
小草cys21 分钟前
HarmonyOS Next调用高德api获取实时天气,api接口
开发语言·python·arkts·鸿蒙·harmony os
爬山算法21 分钟前
Netty(25)Netty的序列化和反序列化机制是什么?
开发语言·python
C+++Python24 分钟前
Java 锁机制
java·开发语言
龘龍龙26 分钟前
Python基础学习(六)
开发语言·python·学习
未来之窗软件服务36 分钟前
幽冥大陆(五十八)php1024位密码生成—东方仙盟筑基期
开发语言·算法·仙盟创梦ide·东方仙盟
悠哉悠哉愿意42 分钟前
【EDA学习笔记】电子技术基础知识:基本元件
笔记·嵌入式硬件·学习·eda
不解风水43 分钟前
【教程笔记】KalmanFilter
笔记·学习·算法·矩阵·ekf