11

我想StructOpt使用枚举,这样每次用户通过-d sunday时,它都会被解析为Day::Sunday

#[macro_use]
extern crate structopt;

use std::path::PathBuf;
use structopt::StructOpt;

// My enum
enum Day {
    Sunday, Monday
}

#[derive(Debug, StructOpt)]
#[structopt(name = "example", about = "An example of StructOpt usage.")]
struct Opt {
    /// Set speed
    #[structopt(short = "s", long = "speed", default_value = "42")]
    speed: f64,
    /// Input file
    #[structopt(parse(from_os_str))]
    input: PathBuf,
    /// Day of the week
    #[structopt(short = "d", long = "day", default_value = Day::Monday)]
    day: Day,
}

fn main() {
    let opt = Opt::from_args();
    println!("{:?}", opt);
}

我目前最好的解决方案是Option<String>用作类型并传递自定义parse_day()

fn parse_day(day: &str) -> Result<Day, ParseError> {
    match day {
        "sunday" => Ok(Day::Sunday),
        _ => Ok(Day::Monday)
    }
    Err("Could not parse a day")
}
4

3 回答 3

25

Struct-opt 接受任何与您的函数FromStr相距不远的implements 类型:parse_day

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"),
        }
    }
}

此外, thedefault_value应该是一个字符串,它将被解释为Dayusing from_str

#[structopt(short = "d", long = "day", default_value = "monday")]
day: Day,
于 2019-02-14T10:09:49.093 回答
19

@kennytm 的方法有效,但arg_enum!宏是一种更简洁的方法,如以下示例所示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);
}

这将让您将工作日解析为Sundaysunday

于 2019-09-30T15:57:59.950 回答
6

错误信息是:

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`

您可以通过实现FromStrfor Day(请参阅kennytm 的答案),如消息所示,或通过定义解析函数来解决这个问题Day

fn parse_day(src: &str) -> Result<Day, String> {
    match src {
        "sunday" => Ok(Day::Sunday),
        "monday" => Ok(Day::Monday),
        _ => Err(format!("Invalid day: {}", src))
    }
}

try_from_str并用属性指定它:

/// Day of the week
#[structopt(short = "d", long = "day", parse(try_from_str = "parse_day"), default_value = "monday")]
day: Day,
于 2019-02-14T10:10:38.127 回答