Shared State Patterns
Cell Attempt Counter
Update a Copy Value
Cell<T> supports interior mutation for small copyable values without taking a mutable reference.
Program
Play the program to choose how many attempts update the shared counter.
cell_attempt_counter.rs
use std::cell::Cell;
fn main() {
let retries = ;
let attempts = Cell::new(0);
for _ in 0..retries {
attempts.set(attempts.get() + 1);
}
println!("attempts={}", attempts.get());
}
use std::cell::Cell;
fn main() {
let retries = ;
let attempts = Cell::new(0);
for _ in 0..retries {
attempts.set(attempts.get() + 1);
}
println!("attempts={}", attempts.get());
}
use std::cell::Cell;
fn main() {
let retries = ;
let attempts = Cell::new(0);
for _ in 0..retries {
attempts.set(attempts.get() + 1);
}
println!("attempts={}", attempts.get());
}
Cell
`Cell` lets code replace a copyable value even through a shared binding.
get
`get` reads the current copy of the value.
set
`set` writes a replacement value back into the cell.