RefCell & Cell
Cell<T> for Copy values without borrow tracking. RefCell<T> runtime-enforces & / &mut rules for non-Copy data.
Busca en todas las páginas de la documentación
Cell<T> for Copy values without borrow tracking. RefCell<T> runtime-enforces & / &mut rules for non-Copy data.
use std::cell::Cell;
fn main() {
let c = Cell::new(0);
c.set(c.get() + 1);
println!("{}", c.get());
}When to reach for this: Mutate through shared handle in single-threaded code when borrow checker blocks.
use std::cell::RefCell;
struct Cache {
hits: RefCell<u32>,
}
impl Cache {
fn hit(&self) {
*self.hits.borrow_mut() += 1;
}
fn hits(&self) -> u32 {
*self.hits.borrow()
}
}
fn main() {
let c = Cache { hits: RefCell::new(0) };
c.hit();
println!("{}", c.hits());
}What this demonstrates:
&self methods mutating interior via RefCellborrow / borrow_mut runtime checksborrow_muttry_borrow for non-panicking. Ref/RefMut guards deref to inner. Not Sync - single thread.
Sync. Fix: Mutex.RefCell or UnsafeCell (unsafe).| Alternative | Use When | Don't Use When |
|---|---|---|
Mutex | Threads | Single-threaded |
Atomic* | Integer flags | Complex types |
Split fields &mut | Compile-time ok | Shared handle required |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026