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() }
    }
相关推荐
陳1030几秒前
C++:list(1)
开发语言·c++
小CC吃豆子1 分钟前
如何在 VS Code 中调试 C++ 程序?
开发语言·c++
Overt0p3 分钟前
抽奖系统(7)
java·开发语言·spring boot·redis·tomcat·rabbitmq
JANG10244 分钟前
【Qt】项目打包
开发语言·qt
Yuer20254 分钟前
批处理不是循环:Rust 量化算子中的 Batch Consistency 与向量化执行语义
rust·金融量化·可控ai
星火开发设计8 分钟前
从公式到应用:卷积公式全面解析与实战指南
学习·算法·机器学习·概率论·知识·期末考试·卷积公式
CoderCodingNo11 分钟前
【GESP】C++五级/六级练习题(前缀和/动态规划考点) luogu-P1719 最大加权矩形
开发语言·c++·动态规划
全栈前端老曹11 分钟前
【包管理】npm最常见的10大问题故障和解决方案
前端·javascript·rust·npm·node.js·json·最佳实践
实战项目12 分钟前
云原生中间件的消息队列性能优化
学习
学嵌入式的小杨同学15 分钟前
循环队列(顺序存储)完整解析与实现(数据结构专栏版)
c语言·开发语言·数据结构·c++·算法