I should prefix this with the fact that I am a rust noob and still trying to figure things out so if I am making a dumb-ass mistake I apologize for that from the start.
I have two structures each containing vector properties.
pub struct Hand {
pub player_id : String,
pub cards : Vec<Card>
}
and
pub struct Deck {
pub cards: Vec<Card>
}
I have a method on the deck that removes a card from the deck and adds it to the hand
pub fn deal(&self, hands: &mut Vec<Hand>, cards: &mut Vec<Card>, quantity: i8) {
for _i in 1..=quantity {
for hand in hands.iter() {
let card = cards.remove(0);
hand.cards.push(card);
}
}
}
This does not work
cannot borrow `hand.cards` as mutable, as it is behind a `&` reference
I tried creating a function to simplify things a bit
fn add_card_to_hand(hand_collection: &mut Vec<Card>, card_collection: &mut Vec<Card>, index: usize) {
let card = card_collection.remove(index);
hand_collection.push(card);
}
and changed the deal function to
pub fn deal(&self, hands: &Vec<Hand>, quantity: i8) {
let mut cardCollection = &self.cards;
for _i in 1..=quantity {
for hand in hands.iter() {
let mut handCollection = &hand.cards;
add_card_to_hand(&mut handCollection, &mut cardCollection, 0);
}
}
}
but now I get this error
error[E0596]: cannot borrow data in a `&` reference as mutable
--> src\cards\deck.rs:63:36
|
63 | add_card_to_hand(&mut handCollection, &mut cardCollection, 0);
| ^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
So the question is this.
What is the right pattern that I should follow when I want to move an element from one vector to another vector that exists on different structures?
The whole can borrow can't borrow thing is confusing.
Is there a great tutorial video reference that can be reconmended.