BONUS: Borrowing Puzzles in Rust

| βŒ› 1 minute read

πŸ“‹ Tags:


In class, we discussed about Rust’s shared-xor-mutable model.

You can only have either:

  • ONE mutable borrow
  • Multiple immutable borrows

There might be some common misconception if you are not aware of ‘non-lexical-lifetimes’.

Consider this:

0
1
2
3
let mut x = 1;
let mut y = &mut x;
let z = &x;
x += 1

What will be the value of x?

A: 2
B: Compile error
C: Panics

Answer: x will successfully increment to 2!

If you don’t believe the output, run it on the rust playground.

This happens because the lifetime of references for both &mut and & are tied to the last use of the reference. This is due to ‘Non-Lexical-Lifetime’.

The Rust book summarises this nicely:

Note that a reference’s scope starts from where it is introduced and continues through the last time that reference is used.

So, the scope/lifetime of y and z in the example are effectively just the line that they were created.

This is typically not an issue you will face day-to-day while coding in Rust for your assignment or this class, but it is worth knowing this rule exists.

I wrote a more in-depth technical article about this with many extra puzzles for you to test your understanding. Link here.