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() }
    }
相关推荐
中国搜索直付通13 小时前
避开直付通选型暗礁:二级商户的合规生存与背景甄别
java·大数据·开发语言·人工智能·游戏
云空13 小时前
《Three.js 可操控3D魔方(键盘转动+打乱+复原)》
javascript·学习·游戏·3d·three.js
Hesionberger13 小时前
LeetCode406:重建身高队列精髓解析
开发语言·数据结构·python·算法·leetcode
kdxiaojie13 小时前
Linux 驱动研究 —— V4L2 (3)
linux·运维·笔记·学习
Qimooidea14 小时前
祁木 CAD Translator 深度评测:从参数解析到工程交付实战
java·开发语言·人工智能·机器翻译
小白学大数据14 小时前
企业内网场景下 Python 自定义 CA 证书信任链的正确配置方法
开发语言·网络·python·信任链
Java面试题总结14 小时前
使用 Python 在 Excel 中添加和自定义文本框
开发语言·python·excel
十月的皮皮14 小时前
C语言学习笔记20260717-预处理机制
c语言·笔记·学习
geovindu14 小时前
CSharp: Recursion Algorithm
开发语言·后端·算法·c#·递归算法
dsyyyyy110114 小时前
用JavaScript实现排序算法
开发语言·javascript·排序算法