gpt4 book ai didi

rust - 当没有提供命令时,Clap 有什么直接的方法来显示帮助吗?

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

我正在使用 the Clap crate用于解析命令行参数。我定义了一个子命令 ls那应该列出文件。 Clap 还定义了一个 help显示有关应用程序及其使用情况的信息的子命令。

如果没有提供命令,则什么也不会显示,但我希望应用在这种情况下显示帮助。

我试过这段代码,它看起来很简单,但它不起作用:

extern crate clap;

use clap::{App, SubCommand};

fn main() {
let mut app = App::new("myapp")
.version("0.0.1")
.about("My first CLI APP")
.subcommand(SubCommand::with_name("ls").about("List anything"));
let matches = app.get_matches();

if let Some(cmd) = matches.subcommand_name() {
match cmd {
"ls" => println!("List something here"),
_ => eprintln!("unknown command"),
}
} else {
app.print_long_help();
}
}

我得到一个错误 app移动后使用:

error[E0382]: use of moved value: `app`
--> src/main.rs:18:9
|
10 | let matches = app.get_matches();
| --- value moved here
...
18 | app.print_long_help();
| ^^^ value used here after move
|
= note: move occurs because `app` has type `clap::App<'_, '_>`, which does not implement the `Copy` trait

通读 Clap 的文档,我发现 clap::ArgMatchesget_matches() 中返回有一个方法 usage 返回使用部分的字符串,但不幸的是,只有这部分,没有其他。

最佳答案

使用clap::AppSettings::ArgRequiredElseHelp :

App::new("myprog")
.setting(AppSettings::ArgRequiredElseHelp)

另见:

关于rust - 当没有提供命令时,Clap 有什么直接的方法来显示帮助吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49290526/

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