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() }
    }
相关推荐
yongui478346 分钟前
MATLAB 使用遗传算法求解微电网优化配置数学模型
开发语言·matlab
郝学胜-神的一滴9 分钟前
Python 抽象基类深度解析:从简易模拟到 abc 模块的优雅实践
开发语言·python·pycharm
AI绘画哇哒哒18 分钟前
RAG 系统中文档切分策略:如何选择合适的 chunk size?| 收藏这份实用指南,小白也能轻松上手大模型学习
人工智能·学习·ai·程序员·大模型·产品经理·转行
xcLeigh19 分钟前
IoTDB Rust 原生接口开发指南:从零生成 + 完整 RPC 调用
数据库·rpc·rust·接口·api·时序数据库·iotdb
Python伍六七21 分钟前
给予Python开发的【16款高效办公自动化工具合集】,告别低效加班!
开发语言·python·自动化
rit843249929 分钟前
基于博弈论的小区分簇算法MATLAB实现
开发语言·算法·matlab
怕什么真理无穷36 分钟前
C++面试5_ TCP 粘包2(工业级)
开发语言·c++·tcp/ip
qingyulee39 分钟前
python redis
开发语言·redis·python
努力努力再努力wz40 分钟前
【MySQL 进阶系列】拒绝滥用root:从 mysql.user 到权限校验,带你彻底理解用户管理与授权机制!
android·c语言·开发语言·数据结构·数据库·c++·mysql