I have 3 structs Player
, Dealer
and Cards
. Dealer
contains a vec of Cards whiles Player
contains a vec of references to some of those cards that the dealer has.
pub struct Dealer{
cards: Vec<Card>,
}
pub struct Player<'a>{
pub cards: Vec<&'a Card>,
}
I have some methods that I implemented for Dealer and Player to create a dealer and a vec of players respectively.
impl Dealer{
pub fn new() -> Self{
//Some code here
}
}
impl Player<'_>{
pub fn create(number: i32) -> Vec<Self>{
//Some code here
}
}
Now I wish to write a function that would iteratively add items to each player's vec.
The function below retrieves a reference to a Card
item in the dealer's vec.
pub fn draw_next(&self) -> &Card{
self.cards.get(//index would be here).unwrap()
}
For now you may disregard the value I use as index.
This is how I add the items to each player's vec.
let d: Dealer = Dealer::new();
let players: Vec<Player> = Player::create(4);
for each_player in players.iter_mut(){
each_player.cards.push(d.draw_next());
}
This executes without any issue however when I change the draw_next
to this:
But for some reason, I need a mutable reference at draw_next
pub fn draw_next(&mut self) -> &Card{
self.cards.get(//index would be here).unwrap()
}
but when I run this:
let mut d: Dealer = Dealer::new();
let players: Vec<Player> = Player::create(4);
for each_player in players.iter_mut(){
each_player.cards.push(d.draw_next());
}
I get this error:
error[E0499]: cannot borrow `d` as mutable more than once at a time
`d` was mutably borrowed here in the previous iteration of the loop
Why is the above code giving me the above error?
I do not expect this error because the following code doesn't give me any errors
struct SS{
i: i32,
}
impl SS{
fn do_this(&mut self){
}
}
fn main(){
let mut name: SS = SS{i: 4};
for _ in 0..3{
name.do_this();
}
}
although they both make use of mutable references in a loop.
For my complete code:https://github.com/nisaacdz/Poker_game/tree/master/src