RUST练习:RefCell和RefMut

         {//mutref

//下面的rentals编译自动判断为RefMut<Vec<Rentals>>但该类型无法显式的标记出来
            let mut rentals = (*storefront.0).borrow_mut();
            if let Some(car) = rentals.get_mut(0) {
                assert_eq!(car.status, Status::Available);
                car.status = Status::Rented;
            }
        }

use std::borrow::BorrowMut;
use std::cell::RefCell;
use std::ops::Deref;
use std::rc::Rc;

#[derive(Debug)]
enum Vehicle{
    Car,
    Truck,
}

#[derive(Debug, Hash, PartialOrd, PartialEq)]
enum Status{
    Available,
    Unavailable,
    Rented,
    Maintenance,
}
struct Rentals{
    status: Status,
    vehicle: Vehicle,
    vin: String,
}

struct Corporate(Rc<RefCell<Vec<Rentals>>>);

struct StoreFront(Rc<RefCell<Vec<Rentals>>>);

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn update_status() {
        let vehicles = vec![
            Rentals {
                status: Status::Available,
                vehicle: Vehicle::Car,
                vin: "A123-367".to_string(),
            },
            Rentals {
                status: Status::Maintenance,
                vehicle: Vehicle::Truck,
                vin: "C652-155".to_string(),
            },
        ];

        let vehicles: Rc<RefCell<Vec<Rentals>>> = Rc::new(RefCell::new(vehicles));
        let corporate: Corporate = Corporate(Rc::clone(&vehicles));
        let storefront: StoreFront = StoreFront(Rc::clone(&vehicles));
        {//mutref
            let mut rentals = (*storefront.0).borrow_mut();
            if let Some(car) = rentals.get_mut(0) {
                assert_eq!(car.status, Status::Available);
                car.status = Status::Rented;
            }
        }
        {//mutref
            let mut rentals = (*corporate.0).borrow_mut();
            if let Some(car) = rentals.get_mut(0) {
                assert_eq!(car.status, Status::Available);
                car.status = Status::Rented;
            }
        }
        let mut rentals = (*storefront.0).borrow();
        if let Some(car) = rentals.get(0) {
            assert_eq!(car.status, Status::Available);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值