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
Replay: real traced execution (multi-file project)
fn main() {
let mut total = 10;
add_bonus(&mut total);
println!("{total}");
}
fn add_bonus(value: &mut i32) {
*value += 5;
}
total ← 10
1fn main() {2 let mut tota→ 10l = 10;3 add_bonus(&mut tota10l);4 println!("{total}");value ← 15, total ← 15
2 let mut total = 10;3 add_bonus(&mut tota→ 15l);4 println!("{total}");5}67fn add_bonus(value: &mut i32) {8 *valu→ 15e += 5;9}output15
Follow the Change
totalstarts at10and is owned bymain.&mut totalgivesadd_bonustemporary permission to change it.*value += 5changes the caller'stotal.- After the call ends,
maincan readtotalagain.
main owns total: 10
add_bonus borrows it: &mut total
after the borrow: 15
&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.
Exercise: mutable_borrow.rs
Write a helper that takes &mut i32, changes the value once, and print the value after the borrow ends