How can I use enums in structopt?
The error message is:
error[E0277]: the trait bound `Day: std::str::FromStr` is not satisfied
--> src/main.rs:22:17
|
22 | #[derive(Debug, StructOpt)]
| ^^^^^^^^^ the trait `std::str::FromStr` is not implemented for `Day`
|
= note: required by `std::str::FromStr::from_str`
You can fix that either by implementing FromStr
for Day
(see kennytm's answer), as the message suggests, or by defining a parse function for Day
:
fn parse_day(src: &str) -> Result<Day, String> {
match src {
"sunday" => Ok(Day::Sunday),
"monday" => Ok(Day::Monday),
_ => Err(format!("Invalid day: {}", src))
}
}
And specifying it with the try_from_str
attribute:
/// Day of the week
#[structopt(short = "d", long = "day", parse(try_from_str = "parse_day"), default_value = "monday")]
day: Day,
Struct-opt accepts any type which implements FromStr
, which is not far away from your parse_day
function:
use std::str::FromStr;
// any error type implementing Display is acceptable.
type ParseError = &'static str;
impl FromStr for Day {
type Err = ParseError;
fn from_str(day: &str) -> Result<Self, Self::Err> {
match day {
"sunday" => Ok(Day::Sunday),
"monday" => Ok(Day::Monday),
_ => Err("Could not parse a day"),
}
}
}
Additionally, the default_value
should be a string, which will be interpreted into a Day
using from_str
.
#[structopt(short = "d", long = "day", default_value = "monday")]
day: Day,
@kennytm's approach works, but the arg_enum!
macro is a more concise way of doing it, as demonstrated in this example from structopt
:
arg_enum! {
#[derive(Debug)]
enum Day {
Sunday,
Monday
}
}
#[derive(StructOpt, Debug)]
struct Opt {
/// Important argument.
#[structopt(possible_values = &Day::variants(), case_insensitive = true)]
i: Day,
}
fn main() {
let opt = Opt::from_args();
println!("{:?}", opt);
}
This will let you parse weekdays as Sunday
or sunday
.