rustHow to create enum from string in Rust
Enums in Rust can be created from strings using the FromStr
trait. This trait is implemented for the str
type, allowing us to convert a string into an enum. To do this, we must first define the enum and implement the FromStr
trait for it. Then, we can use the str::parse
method to convert a string into the enum.
use std::str::FromStr;
#[derive(Debug)]
enum Color {
Red,
Green,
Blue,
}
impl FromStr for Color {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Red" => Ok(Color::Red),
"Green" => Ok(Color::Green),
"Blue" => Ok(Color::Blue),
_ => Err(()),
}
}
}
fn main() {
let color = "Green".parse::<Color>().unwrap();
println!("{:?}", color);
}
Output example:
Green
Explanation
The FromStr
trait is implemented for the str
type, allowing us to convert a string into an enum. To do this, we must first define the enum and implement the FromStr
trait for it. Then, we can use the str::parse
method to convert a string into the enum. In the example above, we define an enum Color
with three variants, and implement the FromStr
trait for it. We then use the str::parse
method to convert the string "Green" into the Color
enum.
Helpful links
Related
More of Rust
- How to use regex to match a group in Rust?
- How to use regex to match a double quote in Rust?
- How to parse JSON string in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to replace strings using Rust regex?
- Regex example to match multiline string in Rust?
- How to get a capture group using Rust regex?
- How to use groups in a Rust regex?
- How to split a string by regex in Rust?
- How to convert a u8 slice to a hex string in Rust?
See more codes...