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() }
    }
相关推荐
传人once几秒前
页面中心圆圈放大效果如何写
开发语言·javascript·ecmascript
NeilYuen3 分钟前
【C++】STL源码仿写(二):vector
开发语言·c++
蜗牛互联网43 分钟前
Python消费Responses SSE事件:增量文本、超时与取消
java·开发语言·人工智能·后端·python
weixin_307779131 小时前
C++代码实现MATLAB中的crossval函数功能
开发语言·c++·算法·matlab
ttwuai1 小时前
Go后台管理系统开源项目:4个官方仓库怎么追溯和核验
开发语言·golang·开源
谢亮_vipxieliang1 小时前
Go Worker Pool 设计——从原理到生产级实现
开发语言·后端·golang
Escalating_xu2 小时前
【C 语言】深入理解指针(5):sizeof、strlen、数组名语义与指针笔试题全解析
java·c语言·开发语言
小雪崩2 小时前
嵌入式学习 day61-62:IMX6ULL驱动——系统移植
学习
Nebula_g3 小时前
JavaSE加强:Stream流
java·开发语言·windows·stream·javase·流
估值探索者3 小时前
【Python量化系统工程实战 #08】从脚本到生产:量化系统上线 checklist 的最小闭环
java·开发语言·jvm·python·数据挖掘·数据·股票数据api接口