Reputation: 4835
This is how far I got:
#[derive(Copy, Clone, Debug)]
enum Suits {
Hearts,
Spades,
Clubs,
Diamonds,
}
#[derive(Copy, Clone, Debug)]
struct Card {
card_num: u8,
card_suit: Suits,
}
fn generate_deck() {
let deck: [Option<Card>; 52] = [None; 52];
for mut i in deck.iter() {
i = &Some(Card {
card_num: 1,
card_suit: Suits::Hearts,
});
}
for i in deck.iter() {
println!("{:?}", i);
}
}
fn main() {
generate_deck();
}
It only prints out None
. Is there something wrong with my borrowing? What am I doing wrong?
Upvotes: 4
Views: 5015
Reputation: 30577
First, your deck is not mutable. Remember in rust bindings are non-mutable by default:
let mut deck: [Option<Card>; 52] = [None; 52];
Next, to obtain an iterator you can modify, you use iter_mut()
:
for i in deck.iter_mut() {
Finally: the i
that you have in your loop is a mutable reference to the elements of deck. To assign something to the reference, you need to dereference it:
*i = Some(Card {
card_num: 1,
card_suit: Suits::Hearts,
});
Upvotes: 9