{//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);
}
}
}