Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create an alias of an enum value?

Tags:

alias

enums

rust

Is there a way to do something like this?

enum MyType {
    Left,
    Right,

    #[cfg(universe = "normal")]
    Port = Left,
    #[cfg(universe = "normal")]
    Starboard = Right,

    #[cfg(universe = "mirror")]
    Port = Right,
    #[cfg(universe = "mirror")]
    Starboard = Left,

}

If you actually try it, you get this error (I had to add MyType::):

error[E0080]: constant evaluation error
 --> <anon>:9:12
  |
9 |     Port = MyType::Left,
  |            ^^^^^^^^^^^^ unimplemented constant expression: enum variants

Here is where that error is triggered.

like image 830
Timmmm Avatar asked Dec 23 '22 21:12

Timmmm


1 Answers

You can use an associated constant to get a constant that looks very similar to an enum variant:

#[derive(PartialEq, Eq)]
pub enum X {
    A,
    B,
}

impl X {
    pub const A1: X = X::A;
}

The associated constant is namespaced inside the enum, just like normal variants. It is compatible with pattern matching — even the unreachable warning and exhaustive matching rules work.

match x {
    X::A1 => ...,
    X::B => ...,
}

playground

There are some limitations: most importantly you can't have any data associated with that value. You also need to #[derive(PartialEq, Eq)] on your struct.

like image 144
CodesInChaos Avatar answered Jan 06 '23 00:01

CodesInChaos