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() }
    }
相关推荐
nashane2 分钟前
HarmonyOS 6学习:JsCrash“闪退”法医指南——从FaultLog堆栈还原崩溃现场的终极手册
学习·华为·harmonyos
for_ever_love__4 分钟前
UI学习:UICollectionView瀑布流
学习·ui·ios·objective-c·cocoa
AOwhisky21 分钟前
MySQL 学习笔记(第六期):MySQL 备份与恢复
运维·数据库·笔记·学习·mysql·云计算
辣椒思密达33 分钟前
Python公开数据采集实战:如何解决请求高频拦截与Session会话中断问题
开发语言·python
_李小白33 分钟前
【android opencv学习笔记】Day 32:直线检测之霍夫变换
android·opencv·学习
Albart5751 小时前
Python 实战教程:用 30 分钟学会解决真实问题
开发语言·python
2301_773643621 小时前
ceph池
开发语言·ceph·python
两年半的个人练习生^_^1 小时前
JMM 进阶:彻底理解 CAS 实现原理
java·开发语言
半个烧饼不加肉1 小时前
JS 底层探究-- 事件循环
开发语言·前端·javascript
asdfg12589632 小时前
C 语言中产生伪随机数的标准做法
c语言·开发语言