Cell<T> lets code update a small Copy value through a shared owner.

Program

Play the program to choose the starting count, store it in a Cell, and update it without making the binding mutable.

start
cell_counter.rs
Replay: real traced execution (multi-file project)
use std::cell::Cell;

fn main() {
    let start = 3;
    let counter = Cell::new(start);
    counter.set(counter.get() + 2);
    let current = counter.get();
    println!("{current}");
}
use std::cell::Cell;

fn main() {
    let start = 1;
    let counter = Cell::new(start);
    counter.set(counter.get() + 2);
    let current = counter.get();
    println!("{current}");
}
use std::cell::Cell;

fn main() {
    let start = 5;
    let counter = Cell::new(start);
    counter.set(counter.get() + 2);
    let current = counter.get();
    println!("{current}");
}
  1. start ← 3, counter ← Cell { value: 3 }, current ← 5

    3fn main() {4    let star→ 3t = 3; //@start=3, 1, 55    let counte→ Cell { value: 3 }r = Cell::new(star3t);6    counter.set(counter.get() + 2);7    let curren→ 5t = counter.get();8    println!("{current}");9}
    output5
  1. start ← 1, counter ← Cell { value: 1 }, current ← 3

    3fn main() {4    let star→ 1t = 1;5    let counte→ Cell { value: 1 }r = Cell::new(star1t);6    counter.set(counter.get() + 2);7    let curren→ 3t = counter.get();8    println!("{current}");9}
    output3
  1. start ← 5, counter ← Cell { value: 5 }, current ← 7

    3fn main() {4    let star→ 5t = 5;5    let counte→ Cell { value: 5 }r = Cell::new(star5t);6    counter.set(counter.get() + 2);7    let curren→ 7t = counter.get();8    println!("{current}");9}
    output7
Cell<T> `Cell<T>` supports interior mutation for values that can be copied in and out.
shared owner The `counter` binding is not `mut`; the cell owns the mutation operation.
get and set `get` copies the current value, and `set` replaces it.