在 Clap 的参数中取多个值 [英] Taking multiple values in an argument in Clap

查看:33
本文介绍了在 Clap 的参数中取多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Clap 并且我正在努力做到这一点子命令可以为参数取多个值.我追求的界面是:

I'm using Clap and I'm trying to make it so that a subcommand can take multiple values for the argument. The interface I'm after is:

just use repo [files]

示例:

just use radar/dot-files gitaliases ryan-aliases

这里的 repo 参数将是字符串radar/dot-files",files 参数将是 ["gitaliases", "ryan-aliases"].

The repo argument here will be the string "radar/dot-files" and the files argument will be a vector of ["gitaliases", "ryan-aliases"].

这是我尝试使用的代码:

Here's the code that I'm trying to use:

let matches = App::new("just")
    .version("v1.0-beta")
    .subcommand(
        SubCommand::with_name("use")
            .arg(Arg::with_name("repo").required(true))
            .arg(
                Arg::with_name("files")
                    .required(true)
                    .multiple(true)
                    .number_of_values(1),
            ),
    )
    .get_matches();

if let Some(matches) = matches.subcommand_matches("use") {
    println!("{:?}", matches.value_of("files").unwrap())
}

这仅输出我指定的第一个文件,而不是所有文件.

This outputs just the first file that I specify, rather than all the files.

对于任意数量的参数,如何让它输出所有不同的文件?

How can I make it output all the different files, for an arbitrary number of arguments?

推荐答案

durka42 from irc.mozilla.org#rust 告诉我使用 values_of 而不是 value_of:

durka42 from irc.mozilla.org#rust told me to use values_of instead of value_of:

let matches = App::new("just")
    .version("v1.0-beta")
    .subcommand(
        SubCommand::with_name("use")
            .arg(Arg::with_name("repo").required(true))
            .arg(Arg::with_name("files").required(true).min_values(1)),
    )
    .get_matches();

if let Some(matches) = matches.subcommand_matches("use") {
    let files: Vec<_> = matches.values_of("files").unwrap().collect();
    println!("{}", files[0]);
    println!("{}", files[1]);
}

如果我愿意,我可能可以使用 iter() 调用来浏览文件.

I could probably use an iter() call to go through the files if I wanted to.

这篇关于在 Clap 的参数中取多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆