HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustModerate

Is there any straightforward way for Clap to display help when no command is provided?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
displayanyprovidedstraightforwardhelpforwaywhencommandclap

Problem

I'm using the Clap crate for parsing command line parameters. I've defined a subcommand ls that should list files. Clap also defines a help subcommand that displays information about the application and its usage.

If no command is provided, nothing gets displayed at all, but I want the app to display help in that case.

I've tried this code, which looks pretty straightforward, but it doesn't work:

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();
    }
}


I get an error that app is used after move:

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


Reading through the documentation of Clap, I've found that the clap::ArgMatches that's returned in get_matches() has a method usage that returns the string for usage part, but, unfortunately, only this part and nothing else.

Solution

Use clap::AppSettings::ArgRequiredElseHelp:

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


See also:

  • Method call on clap::App moving ownership more than once

Code Snippets

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

Context

Stack Overflow Q#49290526, score: 47

Revisions (0)

No revisions yet.