borrowing

Rust Borrow separate struct fields

Rust can distinguish separate fields of a directly accessed struct. Independent field loans let code update different parts of a record without cloning it. Borrowing the whole record would be more restrictive. Expected output (not executed): 25 / 27 Why: Each mutable reference targets a distinct field. Common mistake: Calling a method that takes &mut self while a field loan is still needed; the method signature borrows the whole receiver.

Formal Syntax & Structure

rust syntaxrust
let a = &mut record.first; let b = &mut record.second;

Working Example

Example Snippetrust
struct Budget { food: i32, travel: i32 }fn main() {    let mut budget = Budget { food: 20, travel: 30 };    let food = &mut budget.food;    let travel = &mut budget.travel;    *food += 5;    *travel -= 3;    println!("{food} / {travel}");}
Rust Reference