CodeBlanks Logo Icon CodeBlanks

Borrowing rules

Learn the rules for multiple references at the same time.

Borrowing rules

At any given time, only one of these can be true for a value:

  • any number of &T (readers), or
  • a single &mut T (a writer).
let mut v = vec![1, 2, 3];
let ilk = &v[0];        // a reader
// v.push(4);           // error E0502: can't write while a reader exists
println!("{ilk}");
v.push(4);              // ilk is no longer used, fine

This rule prevents a reference from pointing at an old address after the vector grows and moves to new memory.

Fixing the error

The fix for these errors is usually one of: finishing the use of the reference before the change, copying the value (let ilk = v[0]; is Copy for i32), or separating the operations:

let mut v = vec![1, 2, 3];
let ilk = v[0];          // a copy, not a reference
v.push(ilk * 10);
println!("{:?}", v);     // [1, 2, 3, 10]

Practice Duplicate the first element

Declare let mut v = vec![1, 2, 3];. Take the first element by copying (let ilk = v[0];), then do v.push(ilk * 10); and print with {:?}.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn main() {
    let mut v = vec![1, 2, 3];
    let ilk = v[0];
    v.push(ilk * 10);
    println!("{:?}", v);
}

Expected output

[1, 2, 3, 10]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In the example above, why would <code>v.push(4)</code> fail on the first line?

  • push might move to new memory and ilk would point at an invalid address Correct answer
  • v is immutable
  • 4 is the wrong type
  • It wouldn't fail

Explanation: When capacity runs out, the vector allocates a new array and moves the elements; the borrow checker catches this use-after-free bug at compile time.

2 Fix with a copy

Question
let mut v = vec![5, 6];
let ilk = ____;   // referans değil
v.push(ilk);
Answer
let mut v = vec![5, 6];
let ilk = v[0];   // referans değil
v.push(ilk);

Explanation: v[0] produces a copy for i32, so v can be changed.

3 Case and result

Term Meaning
&v + &v Allowed
&mut v + &mut v E0499
&v + v.push() E0502
let x = v[0]; v.push() Allowed (copy)

All lessons in Beginner