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() }
    }
相关推荐
吃好睡好便好36 分钟前
MATLAB中图像的读取、写入和显示
开发语言·图像处理·学习·计算机视觉·matlab
~kiss~39 分钟前
大模型中的强化学习算法和对齐算法的区别
学习
MartinYeung51 小时前
[论文学习]InjecAgent:工具集成大语言模型智能体的间接提示注入基准测试
网络·学习·语言模型
yaoxin5211231 小时前
476. Java 反射 - 调用方法
java·开发语言
记忆着1 小时前
标准库更多介绍
rust
labixiong1 小时前
React Compiler 用 Rust 重写了,编译提速 10 倍——手写 useMemo 的日子到头了
react.js·rust
猫头虎1 小时前
什么是ZCode for GLM-5.2?
开发语言·人工智能·python·科技·算法·ai编程·ai写作
sean9081 小时前
Vim 学习 - 快速删除/修改
学习·vim
小黄人软件2 小时前
如何解决不想学、学不会、学不进去,吸收内化不了学的东西,怎么办?如何真正建立“知识内化系统“?不输出,不学习
学习
Ivanqhz2 小时前
Rust Lazy浅析
java·javascript·rust