1

This example fails:

fn main() {
    let mut v: Vec<i8> = vec![1, 2];
    v.push(v[0])
}

error message:

error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
 --> src/main.rs:3:12
  |
3 |     v.push(v[0])
  |     -      ^   - mutable borrow ends here
  |     |      |
  |     |      immutable borrow occurs here
  |     mutable borrow occurs here

I knew how to fix this:

let mut v: Vec<i8> = vec![1, 2];
let take = v[0];
v.push(take);

How can I pass an element of a vector as argument for .push() into the same vector without introduction of a temporary variable?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
George Shuklin
  • 6,952
  • 10
  • 39
  • 80

0 Answers0