xxxxxxxxxx
enum MyEnum {
Variant1 = 0,
Variant2 = 4,
Variant3 = 20
}
xxxxxxxxxx
// method 1:
enum Enum {
Foo, // 0
Bar = 9, // 9
Baz // 10
}
// method 2: (for a string enum)
enum Enum {
Foo,
Bar,
Baz,
}
impl std::fmt::Display for Enum {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let out = match self {
Enum::Foo => "FOO",
Enum::Bar => "BAR",
Enum::Baz => "BAZ",
};
write!(f, "{}", out)
}
}
impl std::str::FromStr for Enum {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"FOO" => Ok(Enum::Foo),
"BAR" => Ok(Enum::Bar),
"BAZ" => Ok(Enum::Baz),
_ => Err(format!("Unknown enum value: {}", s)),
}
}
}
fn main() {
let foo: Enum = "FOO".parse().unwrap();
println!("{}", foo.to_string());
let bar: Enum = "BAR".parse().unwrap();
println!("{}", bar.to_string());
let baz: Enum = "BAZ".parse().unwrap();
println!("{}", baz.to_string());
// let qux: Enum = "QUX".parse().unwrap(); // This will panic
// println!("{}", qux);
}
xxxxxxxxxx
// as example a for a gender
enum Gender {
MALE,
FEMININE,
DIVERS,
NONE
}
// impl contains all functions and methods that will be implemented to your enum
impl Gender { }
/* It is possible to give the options variables as well.
An example:
enum Option<T> {
Some(T),
None
}
*/