Rust Fundamentals · 15 XP Pro

The borrowing rules

At any moment a value can have either:

  • any number of shared references (&T), or
  • exactly one mutable reference (&mut T),

but never both at once. This is what lets the compiler promise that nobody reads data while someone else is changing it.

A borrow lasts from where it is created to its last use, not to the end of the block. So you can often fix a conflict by reordering code so the borrows no longer overlap:

let mut v = String::from("hi");
let r = &v;
println!("{r}");      // last use of `r`
let m = &mut v;       // fine: `r` is finished
m.push('!');

Your task

The starter contains two functions that the borrow checker rejects. Fix them without changing their signatures or the results below, and keep both pub.

  • grow_and_measure() must return 11: the length of the text after " world" has been appended to "hello".
  • bump_score() must return 16: start at 10, add 5, then add 1.

Read the compiler error: it points at both conflicting borrows. Hint: take each borrow only when you need it, and let the previous one finish first.

Next lesson →

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