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() }
    }
相关推荐
千寻xun10 小时前
一、理论篇-NVME协议学习笔记
笔记·学习·fpga开发·nvme ssd·nvme协议
researcher-Jiang11 小时前
高性能计算之OpenMP——超算习堂学习1
android·java·学习
西门吹-禅12 小时前
java springboot N+1问题
java·开发语言·spring boot
第一程序员12 小时前
Rust Agent 子进程执行:Command 之前,先定义输入和超时
python·rust·github
skywalk816313 小时前
设计并实现段言的 C FFI 绑定机制 @Trae
c语言·开发语言·python·编程
IT笔记14 小时前
【Rust】Rust Match 模式匹配详解
java·开发语言·rust
2zcode14 小时前
免费开源项目文档:基于MATLAB卷积神经网络的口罩佩戴检测系统
开发语言·matlab·cnn
逝水无殇14 小时前
C# 运算符重载详解
开发语言·后端·c#
TPBoreas15 小时前
配置信息防泄露方案:.env 环境隔离详解(dotenv-java)
java·开发语言
MartinYeung515 小时前
[论文学习]大语言模型安全综述:攻击、防御、对齐、度量与护栏的深度解析
学习·安全·语言模型