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() }
    }
相关推荐
她和夏天一样热几秒前
【观后感】Java线程池实现原理及其在美团业务中的实践
java·开发语言·jvm
lkbhua莱克瓦242 分钟前
进阶-索引3-性能分析
开发语言·数据库·笔记·mysql·索引·性能分析
郑州光合科技余经理7 分钟前
技术架构:上门服务APP海外版源码部署
java·大数据·开发语言·前端·架构·uni-app·php
篱笆院的狗27 分钟前
Java 中的 DelayQueue 和 ScheduledThreadPool 有什么区别?
java·开发语言
2501_9418091431 分钟前
面向多活架构与数据地域隔离的互联网系统设计思考与多语言工程实现实践分享记录
java·开发语言·python
aloha_7891 小时前
agent智能体学习(尚硅谷,小智医疗)
人工智能·spring boot·python·学习·java-ee
qualifying1 小时前
JavaEE——多线程(4)
java·开发语言·java-ee
科技林总2 小时前
2.2 图论应用
学习
guygg882 小时前
两轮车MATLAB仿真程序的实现方法
开发语言·matlab
陌上明苏2 小时前
.NET学习-依赖注入、配置系统、日志系统
学习