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() }
    }
相关推荐
码匠许师傅2 小时前
【C++三方组件】mbedTLS:面向嵌入式的轻量 TLS
开发语言·c++
迪菲赫尔曼3 小时前
【基础篇 12】把环境与源码接起来:检查 GPU,再安装服务器上的项目
运维·服务器·开发语言·人工智能·python·yolo·目标检测
2601_962885723 小时前
2026 Python 股票数据接口选型指南(横评 + 决策树)
开发语言·python·区块链
Evand J3 小时前
【PMSM例程4】PMSM电阻辨识与模型补偿EKF,MATLAB例程。附下载链接,包运行成功
开发语言·matlab·电机·ekf·卡尔曼·pmsm
王仔小奶3 小时前
Rust 正在接管金融圈?深度拆解一份高薪 FinTech 岗位 JD
开发语言·金融·rust
小王C语言3 小时前
Qt常用控件:多元素控件,纵向列表,表格控件,树状控件
开发语言·qt
fanruitian3 小时前
python 可视化 panda seaborn matplotlib.pyplot
开发语言·python·matplotlib
jnrjian4 小时前
delete file shell 让 AI 写脚本
服务器·开发语言
傅科摆 _ py4 小时前
DP,贪心,堆和栈,二分力扣复习
开发语言·python·算法
kiracrimson4 小时前
栈与队列容器:适配器、deque 与 priority_queue
开发语言·c++·适配器模式