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() }
    }
相关推荐
captain37613 小时前
多线程进阶
java·开发语言·数据库
郑州光合科技余经理19 小时前
代驾系统架构拆解:订单链路、权限组织与私有化源码交付
开发语言·后端·算法·架构·系统架构·uni-app·php
码哥DFS1 天前
二叉树的直径
开发语言·javascript·算法
paopaokaka_luck1 天前
基于springboot3+vue3的企业考勤管理系统(部门树递归、Echarts图形化分析)
开发语言·spring boot·学习·echarts·mybatis·需求分析·代码规范
minglie11 天前
zynq高频小数据量PS闭环 抖动时间的测量
学习
long3161 天前
MySQL 学习练习(配套 01 入门资料)
数据库·学习·mysql
梦雨生生1 天前
java开发工具(学习第一天)
java·开发语言·学习
lanfordxb1 天前
从 Markdown 到图片卡片:MarkCard Studio 的功能设计与官网实现记录
rust·软件工程·ai工具
啊啊啊啊啊!!!!1 天前
【c++】stack和queue的接口使用以及底层实现
开发语言·c++
yiqiefeimeng1 天前
Rust还是Go?编程语言的未来之争
rust·go·编程语言·技术社区·未来之争