如何使用StructOpt将参数解析为Vec而不将其视为多个参数?

时间:2018-04-24 15:27:57

标签: rust structopt

我有这段代码:

#[derive(StructOpt)]
pub struct Opt {
    /// Data stream to send to the device
    #[structopt(help = "Data to send", parse(try_from_str = "parse_hex"))]
    data: Vec<u8>,
}

fn parse_hex(s: &str) -> Result<u8, ParseIntError> {
    u8::from_str_radix(s, 16)
}

这适用于myexe AA BB,但我需要将myexe AABB作为输入。

有没有办法将自定义解析器传递给structopt以将AABB解析为Vec<u8>?我只需要解析第二种形式(没有空格)。

我知道我可以通过两个步骤完成它(在结构中存储到String然后解析它,但我喜欢我的Opt具有所有内容的最终类型的想法。

我尝试了这样的解析器:

fn parse_hex_string(s: &str) -> Result<Vec<u8>, ParseIntError>

StructOpt宏对类型不匹配感到恐慌,因为它似乎产生了Vec<Vec<u8>>

1 个答案:

答案 0 :(得分:3)

StructOpt区分了Vec<T>将始终映射到多个参数:

  

Vec<T: FromStr>

     

选项列表或其他位置参数

     

.takes_value(true).multiple(true)

这意味着您需要一种类型来表示您的数据。将您的Vec<u8>替换为新类型:

#[derive(Debug)]
struct HexData(Vec<u8>);

#[derive(Debug, StructOpt)]
pub struct Opt {
    /// Data stream to send to the device
    #[structopt(help = "Data to send")]
    data: HexData,
}

这会导致错误:

error[E0277]: the trait bound `HexData: std::str::FromStr` is not satisfied
  --> src/main.rs:16:10
   |
16 | #[derive(StructOpt)]
   |          ^^^^^^^^^ the trait `std::str::FromStr` is not implemented for `HexData`
   |
   = note: required by `std::str::FromStr::from_str`

让我们实施FromStr

impl FromStr for HexData {
    type Err = hex::FromHexError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        hex::decode(s).map(HexData)
    }
}

它有效:

$ cargo run -- DEADBEEF
HexData([222, 173, 190, 239])

$ cargo run -- ZZZZ
error: Invalid value for '<data>': Invalid character 'Z' at position 0