How can you iterate and change the values in a mutable array in Rust?

≯℡__Kan透↙ 提交于 2020-12-15 01:56:27

问题


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?


回答1:


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,
});

Playground Link



来源:https://stackoverflow.com/questions/56963011/how-can-you-iterate-and-change-the-values-in-a-mutable-array-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!