Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 967
Nomnom Avatar asked Oct 20 '25 16:10

Nomnom


1 Answers

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

like image 162
harmic Avatar answered Oct 23 '25 05:10

harmic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!