Ownership and Borrowing
Mutable Borrow
Changing Through a Reference
A mutable reference (&mut) lets a function change a value the caller owns. Dereferencing with * reaches the value.
Program
Play the program to add a bonus to total through a mutable reference.
mutable_borrow.rs
fn main() {
let mut total = 10;
add_bonus(&mut total);
println!("{total}");
}
fn add_bonus(value: &mut i32) {
*value += 5;
}
&mut
`&mut total` hands out a mutable reference.
dereference
`*value` reaches the value the reference points to.
in-place change
The owned `total` reflects the change after the call.