gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:59:31 25 4
gpt4 key购买 nike

我有这个代码:

#[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宏因类型不匹配而 panic ,因为它似乎产生了 Vec<Vec<u8>> .

最佳答案

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

Vec<T: FromStr>

list of options or the other positional arguments

.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

关于rust - 如何使用 StructOpt 将参数解析为 Vec 而不将其视为多个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50005507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com