rust - 如何使用 StructOpt 将参数解析为 Vec 而不将其视为多个参数?
问题描述
我有这个代码:
#[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
结构中的 a 然后解析它,但我喜欢我Opt
的所有东西都有最终类型的想法。
我尝试了这样的解析器:
fn parse_hex_string(s: &str) -> Result<Vec<u8>, ParseIntError>
宏对类型不匹配感到恐慌,StructOpt
因为它似乎会产生一个Vec<Vec<u8>>
.
解决方案
StructOpt 区分 aVec<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
推荐阅读
- sql - 如何从存储过程返回失败消息
- jenkins - 用于 Kubernetes 的 Jenkins 插件的容器问题
- python - 从另一个数组初始化数组
- amazon-web-services - AWS CodeBuild 由于 UNAUTHORIZED_OPERATION_DELETE_NETWORK_INTERFACE 错误而失败
- spring - 理解、替换、配置和修改 Spring Rabbit (AMQP) 线程池:问题列表
- c# - 从反应上传文件到webapi c#
- c# - WebView 类 (Windows.UI.Xaml.Controls) 不支持 WPF 中的 WebAuthn
- elixir - 如何在 Liveview 模板中停止页面刷新
- ios - 哪个 RxSwift 运算符用于唯一发出的元素以及如何使用?
- python - 如何在 Selenium python 中复制元素文本