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() }
    }
相关推荐
爱上好庆祝9 分钟前
学习JS第十二天
学习
Upsy-Daisy17 分钟前
IOTA 学习笔记(一):IOTA 是什么?从区块链到 Tangle
笔记·学习·区块链
阿里嘎多学长17 分钟前
2026-05-30 GitHub 热点项目精选
开发语言·程序员·github·代码托管
魔法阵维护师18 分钟前
从零开发游戏需要学习的c#模块,第三十三章(暂停菜单)
学习·游戏·c#
wapicn9920 分钟前
API接口调试笔记:从注册到第一个数据返回,全流程详解
java·开发语言·python·lua
.千余25 分钟前
【Linux】 TCP进阶详解:字节流、粘包问题、异常情况与UDP完整对比2
linux·运维·c语言·开发语言·经验分享·笔记·php
geovindu25 分钟前
python: Bounded Parallelism Pattern
开发语言·python·设计模式·有界并行模式
大明者省28 分钟前
Ubuntu Python 部署终极版教程
开发语言·python·ubuntu
光影少年30 分钟前
Redux Toolkit 用法、解决原生Redux 冗余问题
开发语言·前端·javascript·react.js·中间件·前端框架·ecmascript
Upsy-Daisy30 分钟前
IOTA 学习笔记(二):DAG 与 Tangle 到底是什么?
笔记·学习