blonk
July 29, 2020, 9:41pm
1
What's an idiomatic way to convert strings to an enum and enum to a string?
Beginning with the string to enum I tried:
use std::convert::TryFrom;
#[derive(Debug,Clone)]
pub enum FSOType {
Reg,
Dir,
Sym
}
impl TryFrom<&str> for FSOType {
type Error = &'static str;
fn try_from(s: &str) -> Result<Self, Self::Error> {
match s {
"reg" => Ok(FSOType::Reg),
"dir" => Ok(FSOType::Dir),
"sym" => Ok(FSOType::Sym),
_ => Err("Unknown FSOType")
}
}
}
While this compiles I end up in the awkward situation of not actually being able to call it.
mpol
July 29, 2020, 10:06pm
2
Did you try to call it like this? What was the problem?
fn main() {
let reg = FSOType::try_from("reg").unwrap();
println!("{:?}", reg);
}
1 Like
blonk
July 29, 2020, 10:15pm
3
Argh! I was doing it right all along, but I didn't read the final lines of the error output.
help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
5 | use std::convert::TryFrom;
(I have the enum and TryFrom
in a separate module).
L.F
July 30, 2020, 3:35am
4
For this case, it's better to use FromStr
:
use anyhow::{bail, Result};
use std::str::FromStr;
impl FromStr for FSOType {
type Error = anyhow::Error;
fn from_str(s: &str) -> Result<Self> {
match s {
"reg" => Ok(FSOType::Reg),
"dir" => Ok(FSOType::Dir),
"sym" => Ok(FSOType::Sym),
_ => bail!("Unknown FSOType"),
}
}
}
It's recommended that error types implement Error
. Here, I used anyhow::Error
for simplicity.
Now, you can simply use parse
to parse strings into FSOType
.
1 Like
system
Closed
October 28, 2020, 3:35am
5
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.