这是我走了多远:
#[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();
}
它仅打印出None
。我的借款有问题吗?我在做什么错了?
答案 0 :(得分:5)
首先,您的牌组不可变。请记住,在锈绑定中默认情况下是不可更改的:
let mut deck: [Option<Card>; 52] = [None; 52];
接下来,要获取可以修改的迭代器,请使用iter_mut()
:
for i in deck.iter_mut() {
最后:循环中的i
是对Deck元素的可变引用。要将某些内容分配给引用,您需要取消引用:
*i = Some(Card {
card_num: 1,
card_suit: Suits::Hearts,
});