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() }
    }
相关推荐
青柠之夏cc7 分钟前
AI与教育:个性化学习助手让“因材施教“成为现实,但代价是隐私?
人工智能·学习
YOLO数据集集合16 分钟前
EvoAgent:面向PR研发治理的自进化Multi-Agent Harness系统
java·开发语言·目标检测·agent·自进化
for_ever_love__1 小时前
机器学习入门——手写线性回归与梯度下降
人工智能·python·学习·机器学习·线性回归
在猴站学算法1 小时前
(SQL注入学习)无回显的报错注入(Error-Based)
学习·网络安全·sql注入·ctf竞赛
知识分享小能手3 小时前
C++ 学习教程,从入门到精通,C++ 友元、异常和其他特性 — 详细知识点(15)
开发语言·c++·学习
朝朝辞暮i3 小时前
C++ 第 26 课:对象、指针与 ->
java·开发语言·c++
fanged3 小时前
Camera学习2(V4L2和Media Controller)(TODO)
学习
2601_962885724 小时前
如何用 Python 做股价历史分位选股?(筛出处于历史低位的股票)
开发语言·python
殷色玫瑰4 小时前
C++入门基础复习:从命名空间到引用与nullptr,一篇重新捡回C++基础
java·开发语言·c++
(Charon)4 小时前
【C++面试】手写线程池:任务队列、工作线程与优雅退出
开发语言·c++