Interior Mutability Concepts
Cell
Mutating a Copy Value
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.
cell_counter.rs
use std::cell::Cell;
fn main() {
let start = ;
let counter = Cell::new(start);
counter.set(counter.get() + 2);
let current = counter.get();
println!("{current}");
}
use std::cell::Cell;
fn main() {
let start = ;
let counter = Cell::new(start);
counter.set(counter.get() + 2);
let current = counter.get();
println!("{current}");
}
use std::cell::Cell;
fn main() {
let start = ;
let counter = Cell::new(start);
counter.set(counter.get() + 2);
let current = counter.get();
println!("{current}");
}
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.