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() }
    }
相关推荐
RD_daoyi7 小时前
GEO优化能为企业带来哪些价值?
大数据·人工智能·学习·搜索引擎·chatgpt
Jun6268 小时前
QT(5)-第三方日志系统
开发语言·数据库·qt
冰暮流星8 小时前
javascript建立对象之构造函数
开发语言·javascript·ecmascript
RD_daoyi8 小时前
Google SEO 第六周:外链建设与网站权重提升 —— 让排名直冲首页的终极推力
大数据·学习·搜索引擎
AI_零食8 小时前
甄嬛人物日志-朗读升级 - 鸿蒙PC Electron框架完整技术实现指南
前端·学习·华为·electron·鸿蒙·鸿蒙系统
keykey6.8 小时前
PyTorch 入门实战:从张量到训练循环
开发语言·人工智能·深度学习·机器学习
消失的旧时光-19438 小时前
Kotlin 协程设计思想(七):为什么 Kotlin 要设计 SupervisorJob 和 supervisorScope?
android·开发语言·kotlin
MageGojo8 小时前
基于 Rust + Headless Chrome 的自动化文章发布系统设计与登录态持久化实现
自动化测试·rust·桌面应用·headless-chrome·gpui
Full Stack Developme8 小时前
SpringMVC multipart 文件上传
java·开发语言
得一录8 小时前
ModuleNotFoundError: No module named ‘llama_index.llms
开发语言·人工智能