The posts above are mistaken:
The enum Foo
- as the variant name Bar
- and the variant number 1. Rust does not require to set a number. But if you want to check the values e.g. from a database it makes sense to use (and control) the numer and not the name.
As I understood; you need the enum.value (value) of an enum variant
Here is a working solution for your example:
use std::fmt;
#[derive(Debug)]
enum Foo {
Bar = 1,
}
//The to_string() method is available because, Rust automatically implements it for any type that implements Display.
impl fmt::Display for Foo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self) // or fmt::Debug::fmt(self, f) // prints "Bar" NOT the value
}
}
// here are 2 strings, one for the Variant "Bar" and one for the value "1"
let value_of_foo_bar_enum_as_string:String=(Foo::Bar as i32).to_string();
let enum_variant_as_string:String=Foo::Bar.to_string(); //requires impl fmt::Display for Foo above
println!("Enum Foo: variant ->{}<- has value ->{}<-", Foo::Bar, (Foo::Bar as i32).to_string());
// or
println!("Enum Foo: variant ->{enum_variant_as_string}<- has value ->{value_of_foo_bar_enum_as_string}<-");
// Both prints out "Enum Foo: variant ->Bar<- has value ->1<-
assert_eq!(Foo::Bar.to_string(),"Bar");
assert_eq!((Foo::Bar as i32).to_string(),"1"); // default is i32, can be replaced with u8
Have fun!
Martin