1,725
社区成员




上一条:Cell 下一条:Mutex/RwLock
对于没有实现`Copy`的类型,例如`String`和`Vec<T>`,要实现多个不可变借用内部成员的可变性,就需要使用`RefCell<T>`,常用方法主要是
虽然获得了对不可变借用内部成员的可变修改能力,但是借用的规则然起作用,下面是一组单元测试,注意RefCell的借用规则在编译期不会检查,但是运行期会检查,如果违反会在运行期 panic。
测试1:x 一旦borrow_mut,就不可同时 borrow
fn test1(){
let x = RefCell::new(5);
let a = x.borrow();
let b = x.borrow_mut(); // 运行期 panic
}
测试2:x 的borrow可多次
fn test2(){
let x = RefCell::new(5);
let a = x.borrow();
let b = x.borrow();
}
测试3:y 是 x的clone,x 和 y 都可多次borrow
fn test3(){
let x = RefCell::new(5);
let a = x.borrow();
let b = x.borrow();
let y = x.clone();
let c = y.borrow();
let d = y.borrow();
}
测试4:y 是 x的clone,x 和 y 一起,只能有一个borrow_mut
fn test4(){
let x = RefCell::new(5);
let a = x.borrow_mut();
let y = x.clone();
let c = y.borrow_mut();// 运行期 panic
}
测试5:y 是 x的clone,x 和 y 一起,可多次borrow
fn test5(){
let x = RefCell::new(5);
let a = x.borrow();
let y = x.clone();
let c = y.borrow_mut();
}
测试6:y 是 x的clone,x 和 y 一起,只能有一个borrow_mut,可变借用在超出作用域后归还,即可再次可变借用
fn test6(){
let x = RefCell::new(5);
let y = x.clone();
{
let a = x.borrow_mut();
}
let c = y.borrow_mut();
}