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() }
    }
相关推荐
郑州光合科技余经理8 小时前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1239 小时前
matlab画图工具
开发语言·matlab
西岸行者9 小时前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
dustcell.9 小时前
haproxy七层代理
java·开发语言·前端
norlan_jame9 小时前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone9 小时前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054969 小时前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月9 小时前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
悠哉悠哉愿意10 小时前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
番茄灭世神10 小时前
Rust学习笔记第2篇
rust·编程语言