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() }
    }
相关推荐
Zenova EdgeOS7 分钟前
C++ 工业边缘 Boost.Asio 高级实战
开发语言·c++·边缘计算·工业网关
mqiqe11 分钟前
AgentScope Java 2.0 技能仓库(Skill Repository)完全实战指南
java·开发语言·elasticsearch
人工干智能11 分钟前
科普:Python中的生成器——带`yield`的函数
开发语言·python
whcyhhh13 分钟前
头歌实践教学平台:数据科学与大数据技术导论(十四)
大数据·开发语言·python
k4m7v2pz19 分钟前
用 Rust 重造 Java 的 CLI 分发体验:从 java -jar 到 wasmtime run
rust·跨平台·webassembly·wasmtime·wasi·java-jar
淼澄研学26 分钟前
GPT-4o及mini模型参数解析与Python API调用实操
开发语言·python
春风解人意29 分钟前
从零开始学习嵌入式P29----线程间的通信
c语言·嵌入式硬件·学习
kmomo..30 分钟前
Linux 进程学习笔记
linux·笔记·学习
白猫不黑32 分钟前
运维如何转安全(个人经验篇)
运维·学习·安全·web安全·网络安全·信息安全
独立开发之道1 小时前
【three.js教程】Three.js 材质详解:从“不反光“到“物理级真实“怎么选
开发语言·javascript·材质