2

Here's some code that I'm having trouble getting to compile:

struct HasVec {
    vec: Vec<u8>,
}

fn get_or_make<'a>(container: &'a mut HasVec) -> &'a mut u8 {
    let ref mut vec = container.vec;
    {
        for element in vec.iter_mut() {
            if *element > 9 {
                return element;
            }
        }
    }
    vec.push(10);
    vec.last_mut().unwrap()
}

The output from the compiler is:

error[E0499]: cannot borrow `*vec` as mutable more than once at a time
   |
8  |             for element in vec.iter_mut() {
   |                            --- first mutable borrow occurs here
...
14 |         vec.push(10);
   |         ^^^ second mutable borrow occurs here
15 |         vec.last_mut().unwrap()
16 |     }
   |     - first borrow ends here


error[E0499]: cannot borrow `*vec` as mutable more than once at a time
   |
8  |             for element in vec.iter_mut() {
   |                            --- first mutable borrow occurs here
...
15 |         vec.last_mut().unwrap()
   |         ^^^ second mutable borrow occurs here
16 |     }
   |     - first borrow ends here

error[E0499]: cannot borrow `*vec` as mutable more than once at a time
   |
8  |             for element in vec.iter_mut() {
   |                            --- first mutable borrow occurs here
...
15 |         vec.last_mut().unwrap()
   |         ^^^ second mutable borrow occurs here
16 |     }
   |     - first borrow ends here

Isn't the borrow supposed to end at the end of the scope on line 13? I haven't found any way to refactor that code that will satisfy the borrow checker. Putting let ref mut vec = container.vec; inside of the code block with the for loop and another right after that block doesn't work and neither does accessing container.vec directly without a ref variable.

I'm using Rust 1.16.0.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Flaise
  • 571
  • 3
  • 11

0 Answers0