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() }
    }
相关推荐
yugi98783814 小时前
基于MATLAB的延迟求和(DAS)波束形成算法实现
开发语言·算法·matlab
冷雨夜中漫步14 小时前
Python入门——字符串
开发语言·python
Yvonne爱编码14 小时前
Java 接口学习核心难点深度解析
java·开发语言·python
JeffDingAI14 小时前
【Datawhale学习笔记】RLHF微调技术及实践
人工智能·笔记·学习
Yupureki14 小时前
《算法竞赛从入门到国奖》算法基础:搜索-记忆化搜索
c语言·c++·学习·算法·深度优先
黎雁·泠崖14 小时前
Java继承入门:概念+特点+核心继承规则
java·开发语言
Chunyyyen14 小时前
【第三十二周】RAG学习02
学习
x70x8015 小时前
Go中nil的使用
开发语言·后端·golang
强子感冒了15 小时前
MySQL学习随笔:数据类型与字段约束
学习·mysql
tritone15 小时前
学习Chef自动化配置管理工具,为了实践环境部署,我选择了**阿贝云**的**免费虚拟主机**和**免费云服务器**来搭建测试平台。
服务器·学习·自动化