I have a Vec<Vec<T>>
(I know it's not ideal; it's from a library). I want to look at pairs of Vec
s in the outer vec and push to each of them, something like this:
let mut foo = vec![
vec![1, 2, 3],
vec![4, 5, 6],
vec![7, 8, 9],
];
for i in foo.len() {
let a = foo.get_mut(i - 1).unwrap();
let b = foo.get_mut(i).unwrap(); // Does not work
let val = 2; // Some computation based on contents of a & b
a.push(val);
b.insert(0, val);
}
Of course, this fails to compile:
error[E0499]: cannot borrow `foo` as mutable more than once at a time
--> foo.rs:6:17
|
5 | let a = foo.get_mut(i - 1).unwrap();
| --- first mutable borrow occurs here
6 | let b = foo.get_mut(i).unwrap(); // Does not work
| ^^^ second mutable borrow occurs here
...
10 | a.push(val);
| - first borrow later used here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0499`.
It's a similar pattern to the std::slice::window()
method, but as far as I can tell you can't get any mutable items in that.
Is there a way to do this that makes the borrow checker happy?