rustmoduleenumsconstantsstatic-variables

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:

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