Cell
: 可以改变值, 不需要mut
修饰 (inherited mutability
).let x = Cell:new(100); x.set(10);
- 有些时候必须要使用
interior mutability
, 比如Rc::Clone
时修改引用计数.
RefCell
: 运行时borrow checker
, 将编译时静态的borrow check
延迟到运行时.Ref
:RefCell
借用引用的 wrapper, 其生命周期不能超过RefCell
RefMut
: mut 引用 wrapper.
Mutex
/RwLock
: 线程安全实现interior mutability
.let x = Mutex::new(100); let mut r = x.lock().unwrap(); *r = 20;
fn t() -> () {
let x = std::cell::Cell::new(100);
x.set(10);
println!("{:?}", x); // Cell { value: 10 }
let x = std::sync::Mutex::new(100);
{
let mut r = x.lock().unwrap();
*r = 20;
}
{
let mut r2 = x.lock().unwrap();
*r2 = 200;
println!("{:?}", x); // Mutex { data: <locked> }
}
println!("{:?}", x); // Mutex { data: 200 }
let x = std::cell::RefCell::new(0);
let w = x.borrow_mut();
// let r = x.borrow(); // panicked at 'already mutably borrowed: BorrowError'
}
keep learning