调用 Clap 的 get_matches 后如何显示帮助?

How can I display help after calling Clap's get_matches?

我遇到了与 相同的问题,但该问题中提出的解决方案对我来说不够好。

如果没有提供参数,

.setting(AppSettings::ArgRequiredElseHelp) 将停止程序,即使没有提供参数,我也需要程序继续执行。我需要另外显示帮助。

你可以写之前的字符串。

use clap::{App, SubCommand};

use std::str;

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 mut help = Vec::new();
    app.write_long_help(&mut help).unwrap();

    let _ = app.get_matches();

    println!("{}", str::from_utf8(&help).unwrap());
}

或者您可以使用 get_matches_safe

use clap::{App, AppSettings, ErrorKind, SubCommand};

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

    let matches = app.get_matches_safe();

    match matches {
        Err(e) => {
            if e.kind == ErrorKind::MissingArgumentOrSubcommand {
                println!("{}", e.message)
            }
        }
        _ => (),
    }
}