Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to declare a vector of enums types inside a module?

I wish to add a static variable to a module so that I can access the variable by doing module_name::variable_name. However, I want this variable to be a vector of enum types.

Here is what I mean:

pub mod cards{
    #[derive(Debug)]
    pub enum SUIT{
        CLUB, DIAMOND, HEART, SPADE,
    }
    
    pub const all_cards: Vec<SUIT> = vec![SUIT::CLUB, SUIT::DIAMOND, SUIT::HEART, SUIT::SPADE];
}

fn main(){
    println!("{:?}", cards::all_cards);
}

But doing the above gives me two errors:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

error[E0010]: allocations are not allowed in constants

and

error[E0015]: cannot call non-const fn `slice::<impl [SUIT]>::into_vec::<std::alloc::Global>` in constants

Is there a way to declare a vector of enums types inside a module?

>Solution :

In this example you can instead use an Array because of fixed size of ALL_CARDS. Playground link

use crate::cards::ALL_CARDS;

pub mod cards {
    #[derive(Debug)]
    pub enum SUIT {
        CLUB,
        DIAMOND,
        HEART,
        SPADE,
    }

    pub const ALL_CARDS: [SUIT; 4] = [SUIT::CLUB, SUIT::DIAMOND, SUIT::HEART, SUIT::SPADE];
}

fn main() {
    println!("{:?}", ALL_CARDS);
}

Vector requires a heap allocation and as error message says "allocation are not allowed in constants". So when you need a global static data which needs to be initialized on heap once during lifetime of a program: have a look at https://crates.io/crates/once_cell or https://crates.io/crates/lazy_static

Note I’m using uppercase for constant value as per Rust naming convention

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading