I am trying to do this year's AOC in Rust (to learn it) and it is exposing how much I don't understand in Rust.
I have a method for a struct:
pub fn transfer(&mut self, other: &mut CrateStack, num_crates: i32) {
for _ in 1..num_crates {
self.contents.push(other.contents.pop().unwrap());
}
}
Then when I call it I have a vector of CrateStacks:
let num_stacks = 9;
let mut crates: Vec<CrateStack> = Vec::with_capacity(num_stacks);
for _ in 0..num_stacks {
crates.push(CrateStack::new());
}
I call this transfer method like so:
crates[stack2 as usize].transfer(&mut crates[stack1 as usize], qty);
But I get this from my beloved rust compiler:
error[E0499]: cannot borrow `crates` as mutable more than once at a time
--> src/main.rs:54:51
|
54 | crates[stack2 as usize].transfer(&mut crates[stack1 as usize], qty);
| ------ -------- ^^^^^^ second mutable borrow occurs here
| | |
| | first borrow later used by call
| first mutable borrow occurs here
While I could solve this by getting rid of the struct completely, I am trying to learn rust.