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() }
    }
相关推荐
小席是个热心肠5 分钟前
AI相关的自我学习
java·人工智能·学习
知无不研2 小时前
lambda表达式的使用(3)
开发语言·c++·lambda
何事误红尘2 小时前
Mqtt学习笔记(一):Mosquitto服务器搭建、MQTTX安装测试
学习
cfm_29143 小时前
SpringAI + Ollama 本地大模型
java·开发语言·人工智能·语言模型
青山是哪个青山3 小时前
LangChain 学习笔记(三):LangSmith 调试与监控
笔记·学习·langchain
C++ 老炮儿的技术栈4 小时前
基于Qt实现轻量化本地音乐播放器
开发语言·c++·qt·c·播放器·音乐
qq_448011164 小时前
C语言中的柔性数组
c语言·开发语言·柔性数组
小白学大数据4 小时前
长周期爬虫的数据一致性:断点续爬 + 事务回滚保障采集质量
开发语言·爬虫·测试工具
那年窗外下的雪.4 小时前
AIDC 学习日志 第 04 天 BGP Underlay 基础与路由选择
服务器·学习·php
蒸蒸yyyyzwd5 小时前
cpp选手备战后端学习笔记day6 秋招笔试题
笔记·学习