RefCell

  • Rustは単一の &mut または 複数の & を持つことがコンパイラレベルで強制されている
    • RefCell<T> はborrow checkを実行時に遅らせる事ができる
    • 本来は安全であるのにコンパイラの制限で表現できないコードがある時に使う
    • RefCell<T>& でも borrow_mut 出来るので 内部可変性パターン と呼ばれている
      • 例: モックオブジェクト

borrow_mut() を実行時に2回やろうとすると panic する.

可変なリストを作る

#[derive(Debug)]
enum List {
    Cons(Rc<RefCell<i32>>, Rc<List>),
    Nil,
}
 
use List::{Cons, Nil};
use std::rc::Rc;
use std::cell::RefCell;
 
fn main() {
    let value = Rc::new(RefCell::new(5));
 
    let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil)));
 
    let b = Cons(Rc::new(RefCell::new(6)), Rc::clone(&a));
    let c = Cons(Rc::new(RefCell::new(10)), Rc::clone(&a));
 
    *value.borrow_mut() += 10;
 
    println!("a after = {:?}", a);
    println!("b after = {:?}", b);
    println!("c after = {:?}", c);
}

参考