Rust中CLAP Parser如何让-t参数解析多值至Vec<String>?
解决Clap中单个选项无法一次性接收多个Vec参数值的问题
你遇到的问题是因为Clap默认情况下,对于Vec类型的选项,需要多次指定选项标志(比如-t emails -t ip)才能收集多个值,而不是在单个-t后直接跟多个参数。
要让-t支持一次性接收多个空格分隔的值,只需要在types字段的#[clap]属性中添加multiple_values(true)即可:
修改后的代码:
use clap::{Parser, Subcommand, Args}; #[derive(Debug, Parser)] #[clap(author, version, about, name = "raf")] pub struct Opts { #[clap(subcommand)] pub cmd: FileOrFolder, } #[derive(Debug, Subcommand)] pub enum FileOrFolder { #[clap(name = "folder")] Folder(FolderOpts), #[clap(name = "file")] File(FileOpts), } #[derive(Args, Debug)] pub struct FolderOpts { /// `path` of the directory in which all files should be redacted, e.g. ./tests/test_files #[clap(parse(from_os_str))] pub path: std::path::PathBuf, /// The type of redaction to be applied to the files, e.g. -t sgNRIC emails #[clap(short, long, multiple_values(true))] pub types: Vec<String>, } #[derive(Args, Debug)] pub struct FileOpts { #[clap(parse(from_os_str))] pub path: std::path::PathBuf, #[clap(short, long, multiple_values(true))] pub types: Vec<String>, }
修改后,执行cargo run -- folder ./tests/test_files -t emails ip就能正确将emails和ip解析到types字段的Vec中了。
另外,如果需要支持逗号分隔的格式(比如-t emails,ip),可以额外添加value_delimiter(',')属性,和multiple_values(true)配合使用即可。
内容的提问来源于stack exchange,提问作者Jim
相关产品推荐
相关产品推荐

