[−][src]Function tao_of_rust::ch05::smart_pointer::inner_mutable
pub fn inner_mutable()
智能指针和所有权: 内部可变性
是一种可以外部不可变但是内部可变的一种容器
Base usage: Cell
use std::cell::Cell; struct Foo { x: u32, y: Cell<u32> } fn main(){ let foo = Foo { x: 1 , y: Cell::new(3)}; assert_eq!(1, foo.x); assert_eq!(3,foo.y.get()); foo.y.set(5); assert_eq!(5,foo.y.get()); }Run
Base usage: RefCell
use std::cell::RefCell; fn main(){ let x = RefCell::new(vec![1,2,3,4]); println!("{:?}", x.borrow()); x.borrow_mut().push(5); println!("{:?}", x.borrow()); }Run
Base usage: RefCell
use std::cell::RefCell; fn main(){ let x = RefCell::new(vec![1,2,3,4]); let mut mut_v = x.borrow_mut(); mut_v.push(5); // thread 'main' panicked at 'already borrowed: BorrowMutError', // let mut mut_v2 = x.borrow_mut(); }Run