Ref Map Projects Borrows Into Fields
Project a RefCell borrow down to a single field with Ref::map and RefMut::map instead of handing out the whole map borrow.
Code
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"));
}How the code works
Ref Map Projects Borrows Into Fields keeps everything in the functions bump, count_of, reset and main.
Watch out for
- A package manager never enters the picture — each call resolves to something built in.
Applying it
Entry signature: fn bump(&self, key: &str)
Plan on labeled output — requests =, missing =, errors after reset = — when the file runs.
The sequence bump, count_of and reset lives in main; running the file triggers it.
Statements that matter
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;
}
Interactive Tools for This Topic
FAQ
- What does Ref Map Projects Borrows Into Fields print when run?
- Execute the whole file; each printed line is prefixed with a label like `requests =`, `missing =`, `errors after reset =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.