How to borrow a field while mutating another field

Use RefCell<T> to borrow one field immutably while mutating another field in the same struct.

You cannot borrow one field immutably while mutating another field in the same struct because Rust requires a mutable borrow of the entire struct to modify any part of it. Use RefCell<T> to enable interior mutability, allowing you to borrow fields independently at runtime.

use std::cell::RefCell;

struct Data {
    a: RefCell<i32>,
    b: RefCell<String>,
}

fn main() {
    let data = Data {
        a: RefCell::new(5),
        b: RefCell::new(String::from("hello")),
    };

    let _borrow_a = data.a.borrow();
    data.b.borrow_mut().push_str(" world");
}