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() }
    }
相关推荐
该学习了咕咕5 小时前
顶刊论文学习笔记
学习
来让爷抱一个6 小时前
Python 异步里混用同步库,事件循环被卡住的全过程
开发语言·python
Linux-lucky6 小时前
45-Linux学习之旅之防火墙与WEB加固
linux·前端·网络·学习·ubuntu
li星野6 小时前
【学习记录】k-Wave 时间步长、CFL 稳定性与参数实验全解析
学习
心祭丫丫9 小时前
【每天一个 Python 小案例17】Python 实现通讯录
开发语言·人工智能·笔记·python·学习
露天赏雪9 小时前
第3篇:Sentinel熔断降级实战:大模型接口抖动时的服务兜底方案
java·开发语言·人工智能·spring boot·spring·servlet·sentinel
yeccheng11 小时前
MySQL 索引超详解:从底层 B+ 树到面试高频考点
java·开发语言·jvm·mysql·面试
联犀12 小时前
纯 Go 的 CAD 开源库 go-cad:直接解析 DWG/DXF,现在也能导出 PDF
开发语言·golang·pdf
Nerd(BUG版)12 小时前
Flutter学习day5--事件手势与命中测试
学习·flutter
zjxtxdy12 小时前
C++面向对象程序开发-类与对象
开发语言·c++