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后端的Ai之路34 分钟前
Anthropic 官方文章《Building always-on agents》构建指南
开发语言·网络·python
船神丿男人1 小时前
从爬楼梯到最小路径和:6 道 C++ 动态规划题的状态设计
开发语言·c++·动态规划
Evand J1 小时前
【MATLAB例程】基于多基站AOA与距离辅助的二维运动目标定位及速度估计,附下载链接
开发语言·matlab·距离·aoa·多基站
数字供应链安全产品选型1 小时前
从自动化扫描到 AI 自主攻防:下一代渗透测试需要突破哪些核心技术?
开发语言·php
我命由我123451 小时前
Excel - Excel 固定列,滚动时该列始终可见
运维·学习·职场和发展·excel·职场发展·运维开发·学习方法
赤生云电竞2 小时前
云电竞GPU虚拟化选型:vGPU与直通架构实践对比
java·开发语言·架构
吹什么轩2 小时前
c++高并发内存池(一):从objectpool到central cache
java·开发语言
汤姆宝库2 小时前
HNSW:分层图上的贪心检索
开发语言·python
minglie13 小时前
劳斯–赫尔维茨定理的证明
学习
GitCode官方3 小时前
本期精选 Rust 开源项目推荐
开发语言·rust·开源·g-star·atomgit