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() }
    }
相关推荐
影寂ldy3 分钟前
C#栈和队列
开发语言·c#
SilentSamsara10 分钟前
SQLAlchemy 2.x:异步 ORM 与数据库迁移 Alembic 完整指南
开发语言·数据库·python·sql·青少年编程·oracle·fastapi
basketball61617 分钟前
C++ static_cast 完全解析
开发语言·c++
魔法阵维护师24 分钟前
从零开发游戏需要学习的c#模块,第三十四章(设置界面)
学习·游戏·c#
子安柠25 分钟前
Go语言并发编程:协程与管道详解
开发语言·后端·golang
程序大视界29 分钟前
【Python系列课程】Python面向对象(下):封装、继承与多态
开发语言·python
Lumbrologist32 分钟前
【C++】零基础入门 · 第 12 节:模板与 STL 入门
开发语言·c++
天月风沙41 分钟前
基于机器视觉的实验室器件仓储系统设计——内蒙古自治区国家级大创工程存档
开发语言·python
24zhgjx-fuhao42 分钟前
虚链路的配置
开发语言·网络·php
FserSuN1 小时前
Machine Learning Specialization - Week 1, 9-20学习总结
人工智能·学习·机器学习