← 中文资源

简体中文版本

Ref::map 把借用投影到字段

Ref::map 与 RefMut::map 把整张 map 的借用收窄成单个字段的守卫:调用方只能看到投影结果,借用暴露面更小,不必交出整张表。

阅读英文原文

实现说明

除了函数 bump、count_of、reset、main,文件里再无其他定义。

使用要点

  • 演示输出是带标签的(requests =、missing =、errors after reset =),每个操作都会留下自己的一行标注。
  • 执行文件,main 会按顺序走完 bump、count_of、reset。

常见问题

运行「Ref::map 把借用投影到字段」会打印什么?

运行文件本身,requests =、missing =、errors after reset = 这些前缀各对应一段演示逻辑。

入口签名:fn bump(&self, key: &str)

核心语句

fn count_of(&self, key: &str) -> Ref<'_, u64> {
    Ref::map(self.counters.borrow(), |m| m.get(key).unwrap_or(&0))
}
fn reset(&self, key: &str) -> RefMut<'_, u64> {
    RefMut::map(self.counters.borrow_mut(), |m| {
        m.entry(key.to_string()).or_insert(0)
    })
}
fn bump(&self, key: &str) {
    let mut map = self.counters.borrow_mut();
    *map.entry(key.to_string()).or_insert(0) += 1;
}

代码示例

use std::cell::{Ref, RefCell, RefMut};
use std::collections::HashMap;

struct Metrics {
    counters: RefCell<HashMap<String, u64>>,
}

impl Metrics {
    fn bump(&self, key: &str) {
        let mut map = self.counters.borrow_mut();
        *map.entry(key.to_string()).or_insert(0) += 1;
    }

    // Ref::map 把整表借用收窄成单个 u64 的借用投影 project
    fn count_of(&self, key: &str) -> Ref<'_, u64> {
        Ref::map(self.counters.borrow(), |m| m.get(key).unwrap_or(&0))
    }

    // RefMut::map 投影出可变字段,守卫仍然持有整张表
    fn reset(&self, key: &str) -> RefMut<'_, u64> {
        RefMut::map(self.counters.borrow_mut(), |m| {
            m.entry(key.to_string()).or_insert(0)
        })
    }
}

fn main() {
    let metrics = Metrics { counters: RefCell::new(HashMap::new()) };
    metrics.bump("requests");
    metrics.bump("requests");

    println!("requests = {}", *metrics.count_of("requests"));
    println!("missing  = {}", *metrics.count_of("errors"));

    *metrics.reset("errors") = 7;
    println!("errors after reset = {}", *metrics.count_of("errors"));
}