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() }
    }
相关推荐
代码民工正电荷6 小时前
JAVA重要知识点和集合
java·开发语言
星恒随风6 小时前
C++11 加餐(4)并发支持库——condition_variable 条件变量与生产者消费者模型
开发语言·c++
利威尔xu6 小时前
Go map 并发十连问:多 goroutine 同时读写触发 fatal error,进程直接崩溃
开发语言·golang
kitsch0x977 小时前
技术学习_Cowrie 蜜罐的响应机制
学习
你不知道我是谁?7 小时前
GESP C++ 补充知识:浮点数格式化输出(%f/%e/%g)与 fmod 浮点余数实战
开发语言·c++
九蝶科技7 小时前
运费分摊的二开实现:BigDecimal 精确分摊 + 尾差补齐 + 暂估调整
开发语言·python
kyrie_sakura8 小时前
大模型学习32 --大模型微调3 -- 分布式训练算法
分布式·学习·算法
Ryan-Zhong8 小时前
一次接入 16 个平台:视频链接元数据解析 API 的 Python 实战与踩坑记录
开发语言·python·dreamweaver
xwz小王子8 小时前
Nature Custom Media 从手术台到厨房:下一代医疗机器人,正在学习“什么时候该放手”
人工智能·学习·机器人
Rabitebla8 小时前
【Linux】 文件系统(五):挂载与软硬链接,多个文件系统怎样组成统一目录树
linux·运维·服务器·c++·笔记·学习·算法