Ref And RefMut Map Project Into Fields

Ref::map and RefMut::map project a RefCell borrow into a single field, so one field can be read or edited without cloning out of the guard.

RustData Integrity

Code

rustsnippet
28 lines
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);
}

Inside the snippet

Ref And RefMut Map Project Into Fields reduces to the function main.

Caveats

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.

Putting it to use

The primary signature is fn main()

Each step announces itself in the output as name via Ref::map:, attempts now:.

Core lines under the microscope

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

Interactive Tools for This Topic

FAQ

What does Ref And RefMut Map Project Into Fields print when run?
No setup needed: run the file and look for labeled lines like `name via Ref::map:`, `attempts now:` in the output.