Mutable borrows in Rust
One mutable borrow at a time, and never alongside a shared one.
fn add_star(total: &mut u32) {
*total += 1;
}
fn main() {
let mut stars = 2;
add_star(&mut stars);
println!("{stars}");
let mut words = vec!["fig".to_string()];
let first = &mut words[0];
first.push_str("s");
println!("{:?}", words);
let a = &words;
let b = &words;
println!("{} {}", a.len(), b.len());
}
How it works
&mutlets a function change what it was handed.- The borrow ends when it is last used, not at the closing brace.
- Shared borrows may overlap; a mutable one may not.
Keywords and builtins used here
add_starfnletmainmutu32
The run, in numbers
- Lines
- 18
- Characters to type
- 307
- Tokens
- 117
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 74 seconds.
Step 2 of 3 in Borrowing, step 5 of 15 in Ownership & borrowing.