Probably not the right question but trying to learn rust and wondering if there's a way to do this without having to copy out first.
I have a Vec<Vec> where the inner vectors are used as stacks. I want to pop N from vector and push to another but in reverse order
let mut stacks: Vec<Vec<i32>>;
....
let end = stacks[from].iter().take(count);
stacks[to].extend(end); // <-- fails to compile
Now I understand why this can't happen - end
uses an immutable borrow and extend needs a mutable one. I know that the 2 stacks are independent but obviously you couldn't take and push to the same stack. So instead I have to "collect" the 2 off the end (e.g. with split_off
but that means creating a new Vec and wondering if there's a way to avoid that?
(This is a simplified example to show the compile error. The original is when I was trying to solve Advent of Code 2022 in Rust , Q5b - The push and pops happen in a loop and can be from and to any one of N stacks, but never to and from the same one.
Edited question to reflect this. Link to full code )