Cell Interior Mutability For Copy Types
Record counters through shared references with Cell: get and set work under &self with compile-time-only checks, ideal for small Copy state.
Code
use std::cell::Cell;
#[derive(Default)]
struct Stats {
hits: Cell<u32>,
misses: Cell<u32>,
}
impl Stats {
// &self 就能写入:Cell 提供「共享引用下的内部可变性」,仅限 Copy 类型
fn record_hit(&self) {
self.hits.set(self.hits.get() + 1);
}
fn ratio(&self) -> f64 {
let total = (self.hits.get() + self.misses.get()) as f64;
if total == 0.0 {
0.0
} else {
self.hits.get() as f64 / total
}
}
}
fn main() {
let stats = Stats::default();
stats.record_hit();
stats.record_hit();
stats.misses.set(1); // 直接 set 也合法
println!("hits: {}", stats.hits.get());
println!("misses: {}", stats.misses.get());
println!("ratio: {:.2}", stats.ratio());
}How the snippet works
The working surface is the functions record_hit, ratio and main — everything else is wiring.
Using it
The primary signature is fn record_hit(&self)
Running the file prints labeled results such as hits:, misses:, ratio: — each operation’s effect is visible in the output.
Treat main as the orchestrator calling record_hit and ratio in a fixed order.
Key statements
fn ratio(&self) -> f64 {
let total = (self.hits.get() + self.misses.get()) as f64;
if total == 0.0 {
0.0
} else {
self.hits.get() as f64 / total
}
}
fn record_hit(&self) {
self.hits.set(self.hits.get() + 1);
}
Interactive Tools for This Topic
FAQ
- What does Cell Interior Mutability For Copy Types print when run?
- Running the file directly is enough — expect labeled output lines such as `hits:`, `misses:`, `ratio:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.