Progrust Library.

// dictionary

RefCell<T>.

RefCell

RefCell<T> は、不変参照を通して値を変更できる**内部可変性(interior mutability)**を実現するスマートポインタです。コンパイル時の借用チェックを回避し、実行時チェックに遅延させます。

基本的な使用方法

use std::cell::RefCell;

fn main() {
    let x = RefCell::new(5);
    *x.borrow_mut() = 6;
    println!("{}", x.borrow());  // 6
}

Rc<T> (Reference Counting) との組み合わせ

use std::rc::Rc;
use std::cell::RefCell;

#[derive(Debug)]
struct Node {
    value: i32,
    next: Option<Rc<RefCell<Node>>>,
}

fn main() {
    let node = Rc::new(RefCell::new(Node {
        value: 1,
        next: None,
    }));
    
    node.borrow_mut().value = 2;  // 内部可変性で変更
}
RefCellが必要な場合
  • グラフやツリーの子ノードへの変更
  • ストラテジーパターンの実装
  • リスナーなどの集約管理

通常は &mut での借用を使うべきです。

この辞書が使われているページ

backlinks 2

  1. 辞書Box
  2. 辞書Rc<T> (Reference Counting)