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() }
    }
相关推荐
落羽的落羽2 小时前
【C++】现代容器: tuple、optional、variant、any、string_view
linux·开发语言·数据结构·c++·人工智能·计算机网络·算法
叼烟扛炮2 小时前
[LangChain] 学习笔记(24):流式不改总耗时,只改「多久看到第一个字」——实测差 3 倍
笔记·学习·langchain
小飞在努力3 小时前
【实现负载均匀在线判题④】接入 cpp-httplib 实现编译服务 HTTP 网络化
c语言·开发语言·c++·笔记·http
炸薯条!3 小时前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python
CappuccinoRose4 小时前
前端开发交互体系 - 汇总篇
开发语言·前端·javascript·css·html·交互
tryCbest4 小时前
Python 爬虫从入门到实战(二):进阶篇——反爬对抗、并发与动态页面
开发语言·爬虫·python
S_WEAN5 小时前
【C++】STL - Priority_queue的使用及模拟实现与仿函数
开发语言·c++
星落梦生5 小时前
Tlias前端案例涉及知识点 (14)
开发语言·前端·javascript
FRing0316 小时前
vue2干货总结12(loading效果、全局前置导航守卫、搜索历史管理)
开发语言·前端·javascript·vue.js·vue2
wefg116 小时前
【项目】C++ 基于 Vibe Coding 的 OJ 平台
开发语言·c++