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() }
    }
相关推荐
青春喂了后端15 小时前
Go Sidecar Status 性能优化
开发语言·性能优化·golang
me83215 小时前
【AI面试】大模型面试60问(面试速记+详解)
人工智能·学习·ai
摇滚侠15 小时前
MyBatis 入门到项目实战 MyBatis 分页插件 65-66
java·开发语言·sql·mybatis
CHHH_HHH15 小时前
【C++】哈希表原理与实战:从冲突解决到性能优化
开发语言·数据结构·c++·学习·算法·哈希算法·散列表
Cloud_Shy61815 小时前
解读《Effective Python 3rd Edition》:从练气到老魔(第七章 Item 48 - 50)
开发语言·人工智能·笔记·python·microsoft·学习方法
秋雨梧桐叶落莳15 小时前
iOS——QQ音乐仿写项目总结
学习·macos·ui·ios·mvc·objective-c·xcode
A__tao15 小时前
告别手写 Go 结构体!推荐一个支持注释解析的 YAML 转 Struct 在线工具
开发语言·后端·golang
何以解忧,唯有..15 小时前
Go 语言语句分隔符详解:分号、换行与代码规范
开发语言·golang·代码规范
人邮异步社区15 小时前
C语言进阶的书籍推荐
c语言·开发语言
编程版小新15 小时前
Day1:体验产品,以画图方式梳理用户操作和管理员操作
学习