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() }
    }
相关推荐
Дерек的学习记录2 小时前
C++:stack和queue
开发语言·c++·学习·算法
烟烟Abandon4 小时前
FFmpeg开发基础之 C 语言 :再论指针(讲透指针)
c语言·开发语言·ffmpeg
阿俊-全栈开发7 小时前
扩展设计解析:LikeShop Go 版商城营销活动的插件化扩展设计思路
开发语言·微服务·golang·likeshop·likeshop源码
干啥啥不行,bug第一名7 小时前
EAFNOSUPPORT、EPROTOTYPE、EOPNOTSUPP:socket 的三层参数没有对齐
开发语言·php
丽丽的代码7 小时前
Docker 命令学习手册:从零接手一个容器化项目
学习·docker·容器
我要见SA姐18 小时前
用生活化类比当钥匙,一键打开 C++ 入门大门
java·开发语言·c++
1024奇点8 小时前
第四篇 第 03 课
开发语言·ide·后端
大彼方..9 小时前
CSDN-02-开发环境介绍与安装
c语言·开发语言·stm32
BK贝壳9 小时前
初始化一亿个全 True 或全 False:bool-hybrid-array 的 TruesArray/FalsesArray 占位构造本机实测
开发语言·数据结构·python·性能优化·numpy
L-影10 小时前
HashMap详解-上篇
java·开发语言·spring·hashmap