Rust Fundamentals · 15 XP Pro

Mutable references

A plain &T lets you read but not change. To modify a borrowed value you need a mutable reference, written &mut T. Two things are required: the variable must be declared mut, and you must lend it with &mut.

Inside the function, * follows the reference to the value it points at. Method calls like push_str do that for you automatically, but for plain numbers you write the * yourself.

fn add_ten(n: &mut i32) {
    *n += 10;
}

fn main() {
    let mut score = 5;
    add_ten(&mut score);
    println!("{score}"); // 15
}

The function returns nothing, yet the caller sees the change, because the function worked on the caller's own value rather than a copy.

Your task

Write two pub functions:

  • add_exclamation(s: &mut String) appends a single '!' to the string.
  • swap_values(a: &mut i32, b: &mut i32) exchanges the two numbers, so that afterwards a holds the old b and vice versa. Use a temporary variable rather than std::mem::swap.

Next lesson →

Sign in to run your code. It's free.