39

I am wondering is it possible to create enum with constant string values in Rust?

I found this previous question: How do I get an enum as a string? which shows a work around that I can use to stringify variants of an enum (I can use .to_string() on enum variants and get their name as a string).

That question was helpful, but this is what I want to achieve:

enum StringEnum {
    Hello = "Hello",
    World = "World"
}
Herohtar
  • 5,347
  • 4
  • 31
  • 41
Krzysztof Kaczyński
  • 4,412
  • 6
  • 28
  • 51
  • 1
    Enum derives from *enumerate*, so it will always want an `isize` for each entry. – C14L Nov 27 '20 at 16:07
  • 1
    @C14L so it is impossible because strings can have different sizes and every `enum` value must be the same size. Am I right ? – Krzysztof Kaczyński Nov 27 '20 at 16:16
  • 1
    Correct. In the answer you linked to, a Crate is mentioned that seems to do what you are looking for: [strum_macros](https://crates.io/crates/strum_macros) – C14L Nov 27 '20 at 16:19
  • 4
    The discriminator of an enum is always an integral type in Rust. Implementing a function returning the string value as an `&'static str` or implementing the `Display` trait like in the linked quest is the way to go. You could use macros to make reduce the boilerplate. – CodesInChaos Nov 27 '20 at 16:21
  • @C14L Yes I saw this dependency, but I am just learning Rust, so I didn't want to use dependencies. Anyway thank you for your answer. If you want to add an answer with explanation, I will accept your answer. – Krzysztof Kaczyński Nov 27 '20 at 16:24

1 Answers1

64

If you have an enum like this:

enum HelloWorld {
    Hello,
    World
}

Hello and World are enum variants. Every variant of an enum is assigned to a single integer value. This is known as the discriminant. Currently, discriminants are only allowed to be integers, not arbitrary types like &'static str, although that may change in the future.

If you want to be able to convert your enum to a string, you can write a method that does this manually:

impl HelloWorld {
    fn as_str(&self) -> &'static str {
        match self {
            HelloWorld::Hello => "Hello",
            HelloWorld::World => "World"
        }
    }
}

Or you can have this done for you with the strum_macros crate:

#[derive(strum_macros::Display)]
pub enum StringEnum {
    Hello,
    World
}


fn main() {
    let hello: &'static str = StringEnum::Hello.into(); // "Hello"
    let world: String = StringEnum::World.to_string(); // "World"
}

There are a couple other methods mentioned in How do I get an enum as a string?

Ibraheem Ahmed
  • 11,652
  • 2
  • 48
  • 54