snippetrustMajor
Can I create string enum?
Viewed 0 times
stringenumcreatecan
Problem
I am wondering is it possible to create
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
That question was helpful, but this is what I want to achieve:
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"
}
Solution
If you have an enum like this:
If you want to be able to convert your enum to a string, you can write a method that does this manually:
Or you can have this done for you with the
There are a couple other methods mentioned in How do I get an enum as a string?
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?
Context
Stack Overflow Q#65040158, score: 99
Revisions (0)
No revisions yet.