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,
}
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
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.
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.
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.
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;
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With