1

I want to store a batch of data somewhere and refer to them from multiple spaces, and I have serious trouble with borrowing:

fn main() {
    let mut v1: Vec<i32> = Vec::new();
    let mut v2: Vec<&i32> = Vec::new();
    for i in 1..10 {
        v1.push(i);
        v2.push(v1.last().unwrap());
    }
    println!("{:?}", v1);
    println!("{:?}", v2);
}

Playground

error[E0502]: cannot borrow `v1` as mutable because it is also borrowed as immutable
  --> src/main.rs:6:9
   |
6  |         v1.push(i);
   |         ^^ mutable borrow occurs here
7  |         v2.push(v1.last().unwrap());
   |                 -- immutable borrow occurs here
...
11 | }
   | - immutable borrow ends here
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 2
    TL;DR the duplicates: You cannot hold a reference to a value of `v1` while you mutate it. Doing so would allow the reference to point to non-allocated memory. You need to split the creation of the vector with values and the creation of the vector of references: `let v1: Vec<_> = (1..10).collect(); let v2: Vec<_> = v1.iter().collect();` – Shepmaster Jan 16 '18 at 17:02

0 Answers0