实现说明
真正干活的是函数 record_hit、ratio、main,其余都是接线。
使用要点
- 演示输出是带标签的(
hits:、misses:、ratio:),每个操作都会留下自己的一行标注。 main的演示流程是record_hit、ratio——跑一遍文件,这条流程从头到尾可见。
常见问题
运行「Cell 提供 Copy 类型的内部可变性」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 hits:、misses:、ratio: 这类标签。
入口签名:fn record_hit(&self)
核心语句
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);
}
代码示例
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());
}