← 中文资源

简体中文版本

Ref 与 RefMut map 投影字段借用

Ref::map 与 RefMut::map 把 RefCell 的借用投影到单个字段:读或改一个字段都不必把整个守卫克隆出来,借用生命周期不变。

阅读英文原文

实现说明

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);
}