Dzwebs.Net

撰写电脑技术杂文十余年

rust之RefCell配合Option和struct可修改缓存

Admin | 2025-2-8 17:32:35 | 被阅次数 | 77

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆
use std::cell::RefCell;
use std::option::Option;
#[derive(Debug)]
struct Rectangle {
    width: f64,
    height: f64,
    cached_area: RefCell<Option>,
}
impl Rectangle {
    //初始化缓存
    fn new(width: f64, height: f64) -> Self {
        Rectangle {
            width,
            height,
            cached_area: RefCell::new(Some(width*height)),
        }
    }
    //取消缓存
    fn cancel_cached_area(&self){
        self.cached_area.replace(None);
    }
    //修改缓存
    fn update_cached_area(&self,area:Option){
        self.cached_area.replace(area);
    }
}
fn main() {
    let rt = Rectangle::new(3.0, 4.0);
    println!("初始化缓存:{:?}",rt.cached_area.take().unwrap());
    let rt = Rectangle::new(4.0, 4.0);
    rt.cancel_cached_area();
    println!("取消缓存:{:?}",rt.cached_area.take());
    rt.update_cached_area(Some(99.9));
    println!("修改缓存:{:?}",rt.cached_area.take());
}
/*输出如下内容
初始化缓存:12.0
取消缓存:None
修改缓存:Some(99.9)
*/

该杂文来自: 最新技术

上一篇:rust之OnceLock配合static和struct构造计算一次的

下一篇:暂时没有文章了

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计