1

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.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
Alan
  • 236
  • 3
  • 11
  • Nitpick: Assuming `CrateStack` impls `Clone`, you can initialize the stacks with `vec![CrateStack::new(); num_stacks]`. – Chayim Friedman Dec 05 '22 at 15:31
  • Thanks @ChayimFriedman - I didn't know that shortcut! – Alan Dec 05 '22 at 17:52
  • Agree that it is the same as the duplicate – Alan Dec 05 '22 at 17:53
  • In terms of solving this, instead of using a custom struct to represent _one_ crate stack, you can use a custom struct that represents the "whole of the crate stacks". Internally, that can then of course be a vector of single crate stacks. But the nice thing then is that, if you define the `move_crates` method (or whatever) for the `CrateStacks` struct, you don't have to pass around mut references to vector elements, while still having a nice encapsulated solution. You can check out my solution at `github.com/cadolphs/aoc_2022` if you're curious how I did exactly that. – cadolphs Dec 05 '22 at 20:45

0 Answers0