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() }
    }
相关推荐
monstercl17 分钟前
【Lua】pcall使用详解
开发语言·lua
气π27 分钟前
【Vue-组件】学习笔记
vue.js·笔记·学习
东方苾梦44 分钟前
SQL语言的计算机体系结构
开发语言·后端·golang
蹦蹦跳跳真可爱5891 小时前
Python----PaddlePaddle(深度学习框架PaddlePaddle,概述,安装,衍生工具)
开发语言·人工智能·python·paddlepaddle
一只专注api接口开发的技术猿1 小时前
京东API智能风控引擎:基于行为分析识别恶意爬虫与异常调用
大数据·开发语言·前端·爬虫
谬了个大也1 小时前
go --- go run main.go 和 go run .
开发语言·后端·golang
可可南木1 小时前
BT-Basic函数之首字母S
开发语言·测试工具·pcb工艺
涛涛讲AI1 小时前
Python urllib3 全面指南:从基础到实战应用
开发语言·python·urllib3
yy_xzz1 小时前
基于条码数据生成校验密码的C++实现方案
开发语言·c++
技术小白Byteman2 小时前
蓝桥刷题note13(排序)
开发语言·数据结构·c++·学习·算法·visualstudio