RRust By Example

Cell and RefCell

Interior mutability with Cell and RefCell.

Cell and RefCell

Interior mutability with Cell and RefCell.

Difficulty

Advanced

Code

rust
use std::cell::RefCell;

fn main() {
    let data = RefCell::new(vec![1, 2, 3]);

    // borrow mutably
    data.borrow_mut().push(4);
    println!("{:?}", data.borrow());

    // borrow immutably multiple times is fine
    let r1 = data.borrow();
    let r2 = data.borrow();
    println!("{:?} {:?}", r1, r2);
}

Explanation

Cell/RefCell enable interior mutability.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the smart-pointers category to build a complete understanding of this topic.

More Smart Pointers Examples