我有这样的代码:
#[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>>。
发布于 2018-04-24 16:20:36
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 0https://stackoverflow.com/questions/50005507
复制相似问题