borrowing

Rust Borrow a mutable function argument

A function can modify the caller’s existing value rather than consume and return a replacement. Its signature explicitly requests exclusive access for the call. Expected output (not executed): 9 Why: The function writes to the original inventory through its parameter. Common mistake: Writing count += amount instead of dereferencing the &mut i32 parameter.

Formal Syntax & Structure

rust syntaxrust
fn update(value: &mut T) { ... }

Working Example

Example Snippetrust
fn restock(count: &mut i32, amount: i32) {    *count += amount;}fn main() {    let mut inventory = 6;    restock(&mut inventory, 3);    println!("{inventory}");}
Rust Reference