typestar

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

  1. &mut lets a function change what it was handed.
  2. The borrow ends when it is last used, not at the closing brace.
  3. Shared borrows may overlap; a mutable one may not.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Borrowing, step 5 of 15 in Ownership & borrowing.

← Previous Next →