Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple enum variants with same value?

Tags:

rust

What is the best way to have multiple enum variants that are the same value? This is an example of what I would like, except that Rust doesn't like it.

pub enum Nums {
    Num1            = 0,
    Num2            = 1,
    Num3            = 2,
    Num4            = 3,
    Num5            = 4,

    FirstNum        = 0,
    MiddleNum       = 2,
    LastNum         = 4,
}
like image 260
Graeme Avatar asked Jun 25 '16 05:06

Graeme


People also ask

Can multiple enums have the same value?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

What is Rust enum?

In Rust, an enum is a data structure that declares its different subtypes. An enum enables the same functionality as a struct, but it does so with less code. For example, implementing different types of Machine , where each machine has a different set of attributes, requires a different struct for each machine.

Do enum values have to be unique?

Show activity on this post. I also found the same idea on this question: Two enums have some elements in common, why does this produce an error? Enum names are in global scope, they need to be unique.

Can enums have methods Rust?

In Rust, methods cannot only be defined on structs, they can also be defined on tuples and enums, and even on built-in types like integers.


2 Answers

enum variants cannot have the same tag value as other variants. As of Rust 1.20, you can use associated constants. This lets you use Nums::FIRST_NUM, etc.

pub enum Nums {
    Num1 = 0,
    Num2 = 1,
    Num3 = 2,
    Num4 = 3,
    Num5 = 4,
}

impl Nums {
    pub const FIRST_NUM: Nums = Nums::Num1;
    pub const MIDDLE_NUM: Nums = Nums::Num3;
    pub const LAST_NUM: Nums = Nums::Num5;
}

Before that, you will need to use constants:

pub const FIRST_NUM: Nums = Nums::Num1;
pub const MIDDLE_NUM: Nums = Nums::Num3;
pub const LAST_NUM: Nums = Nums::Num5;
like image 96
DK. Avatar answered Nov 15 '22 09:11

DK.


You can also add methods to the enum:

pub enum Nums {
    Num1 = 0,
    Num2 = 1,
    Num3 = 2,
    Num4 = 3,
    Num5 = 4,
}

impl Nums {
    pub fn first()  -> Self { Nums::Num1 }
    pub fn middle() -> Self { Nums::Num3 }
    pub fn last()   -> Self { Nums::Num5 }
}

fn main() {
    println!("{}", Nums::first() as u8);
}
like image 42
Shepmaster Avatar answered Nov 15 '22 11:11

Shepmaster