Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over an enum

Tags:

enums

rust

So I'm trying to build a simple deck generator using Rust. I'm new to the language so I haven't grasped everything about it yet.

I want to iterate over both a Suits enum and a Values enum, make a Card struct using them, and then push that Card into the Deck's cards vector.

So far I tried making a static enum and iterating over that like this:

        static SUITE_ITER: [Cards::Suits; 4] = [
          Cards::Suits::HEARTS,
          Cards::Suits::CLUBS, 
          Cards::Suits::DIAMONDS,
          Cards::Suits::SPADES
        ];
        for suit in SUITE_ITER.into_iter() {...}

However, I get this error message that I don't fully understand. Any tips?

cannot move out of static item SUITE_ITER move occurs because SUITE_ITER has type [Suits; 4], which does not implement the Copy trait

like image 798
branperr Avatar asked Sep 01 '25 20:09

branperr


1 Answers

Enum values cannot be copied by default. If you want to make a type "copyable", usually what you can do is annotate it with the Copy proc macro via #[derive(Copy)]. As an alternative, you might want to use references to the values.

Your code uses into_iter. I suggest you read this.

You might also take a look at the strum crate and read this for more info.

like image 99
at54321 Avatar answered Sep 03 '25 23:09

at54321