I have a vector of vectors, and the number of vectors can change at runtime. I therefore have:
struct ItemStruct {
old: usize,
transfer: usize,
}
//...
let number_of_vectors = x.len();
let mut ListOfItems = vec![vec![0; 0]; number_of_vectors];
there is then some code to add to the internal vectors, which all goes fine.
However, later on I need to move items between vectors (inside one vector) and I always trip up from the ownership rules:
for item in anotherList.iter() {
let to_move = ListOfItems[item.old].rchunks(4).next().unwrap();
ListOfItems[item.transfer].append(&mut to_move.to_owned())
}
error[E0502]: cannot borrow `ListOfItems` as mutable because it is also borrowed as immutable
--> src\main.rs:53:9
|
52 | let to_move = ListOfItems[item.old].rchunks(4).next().unwrap();
| ----------- immutable borrow occurs here
53 | ListOfItems[item.transfer].append(&mut to_move.to_owned())
| ^^^^^^^^^^^ mutable borrow occurs here ----------------- immutable borrow later used here
How do I move an item from one vector to another? If I new the number of Vectors at compile time I would do it differently, but because its variable, I have gone with creating a vector of vectors. I know I could do this in C and in Python but I also understand why Rust doesn't like it!