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() }
    }
相关推荐
小灰灰搞电子16 分钟前
Rust Once 、OnceLock、LazyLock 一次性初始化详解
开发语言·后端·rust
hqyjzsb23 分钟前
规划工商管理大学成长:搭建四层能力体系,重视高阶的 AI 能力建设
开发语言·人工智能·python·microsoft·职场和发展·数据挖掘·业界资讯
小叶肥辉32 分钟前
LangChain链和LangGraph图的学习笔记【六】——提示语模板(3)——Few-Shot Prompting(少样本提示) 模板类
笔记·python·学习·langchain·prompt·aigc
qq_4523962343 分钟前
第八篇:《智能指针与内部可变性:Rust 的进阶内存管理》
rust
for_ever_love__43 分钟前
爬虫项目: 获取高分电影的数据总结
开发语言·python·学习
weixin_307779131 小时前
C++代码实现MATLAB中的ode23t函数功能
开发语言·c++·算法·matlab
君顾11 小时前
24小时自助健身房系统开发实战与完整指南
java·开发语言·健身房
syagain_zsx2 小时前
算法基础篇 · 02 高精度(C++ 题解)
开发语言·c++·学习·高精度
白远山2 小时前
无人自助健身平台搭建:从架构设计到设备联动的完整实战
java·开发语言·架构·需求分析
m4Rk_2 小时前
【论文阅读】Agent 记忆机制(72):EMA——在写入前决定什么值得记住
论文阅读·人工智能·学习·开源·github