1

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

Isaac Dzikum
  • 184
  • 9
  • 1
    In your last code snippet, you don't return a reference from `do_this()`, so the mutable borrow for `self` ends when the function returns. The `draw_next()` method, on the other hand, does return a reference to a `Card`, which you persist in `each_player.cards`. This keeps the mutable borrow of `self` active as long as you keep the reference to the `Card`. I suggest making the cards `Copy` and returning `Card` instead of `&Card`. – Sven Marnach Oct 17 '22 at 14:36

0 Answers0