实现说明
Ref 与 RefMut map 投影字段借用可以归结为函数 main。
使用要点
- 每一步打印都带着自己的标签:
name via Ref::map:、attempts now:。
常见问题
运行「Ref 与 RefMut map 投影字段借用」会打印什么?
整个文件跑完,输出行以 name via Ref::map:、attempts now: 这类前缀开头。
核心语句
let mut attempts = RefMut::map(writable, |s| &mut s.attempts);
let name: Ref<str> = Ref::map(borrowed, |s| s.name.as_str());
let mut writable = session.borrow_mut();
代码示例
use std::cell::{Ref, RefCell, RefMut};
struct Session {
name: String,
attempts: u32,
}
fn main() {
let session = RefCell::new(Session {
name: String::from("cache-loader"),
attempts: 0,
});
// Ref::map projects the shared borrow into a single field: no need to clone the whole guard
{
let borrowed = session.borrow();
let name: Ref<str> = Ref::map(borrowed, |s| s.name.as_str());
println!("name via Ref::map: {}", &*name);
}
// RefMut::map projects the exclusive borrow onto the field for in-place mutation
{
let mut writable = session.borrow_mut();
let mut attempts = RefMut::map(writable, |s| &mut s.attempts);
*attempts += 1;
}
println!("attempts now: {}", session.borrow().attempts);
}