Skip to main content

## Command

# Struct Command

Source

    pub struct Command { /* private fields */ }

Expand description

Build a command-line interface.

This includes defining arguments, subcommands, parser behavior, and help output. Once all configuration is complete, the `Command::get_matches` family of methods starts the runtime-parsing process. These methods then return information about the user supplied arguments (or lack thereof).

When deriving a `Parser`, you can use `CommandFactory::command` to access the `Command`.

- Basic API
- Application-wide Settings
- Command-specific Settings
- Subcommand-specific Settings
- Reflection

## §Examples

    let m = Command::new("My Program")
        .author("Me, me@mail.com")
        .version("1.0.2")
        .about("Explains in brief what the program does")
        .arg(
            Arg::new("in_file")
        )
        .after_help("Longer explanation to appear after the options when \
                     displaying the help information from --help or -h")
        .get_matches();

    // Your program logic starts here...

## Implementations§

Source§

### impl Command

#### §Basic API

Source

#### pub fn new(name: impl Into<Str>) -> Command

Creates a new instance of an `Command`.

It is common, but not required, to use binary name as the `name`. This name will only be displayed to the user when they request to print version or help and usage information.

See also `command!` and `crate_name!`.

##### §Examples

    Command::new("My Program")

##### Examples found in repository?

examples/multicall-busybox.rs (line 8)

    6fn applet_commands() -> [Command; 2] {
    7    [
    8        Command::new("true").about("does nothing successfully"),
    9        Command::new("false").about("does nothing unsuccessfully"),
    10    ]
    11}
    12
    13fn main() {
    14    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    15        .multicall(true)
    16        .subcommand(
    17            Command::new("busybox")
    18                .arg_required_else_help(true)
    19                .subcommand_value_name("APPLET")
    20                .subcommand_help_heading("APPLETS")
    21                .arg(
    22                    Arg::new("install")
    23                        .long("install")
    24                        .help("Install hardlinks for all subcommands in path")
    25                        .exclusive(true)
    26                        .action(ArgAction::Set)
    27                        .default_missing_value("/usr/local/bin")
    28                        .value_parser(value_parser!(PathBuf)),
    29                )
    30                .subcommands(applet_commands()),
    31        )
    32        .subcommands(applet_commands());
    33
    34    let matches = cmd.get_matches();
    35    let mut subcommand = matches.subcommand();
    36    if let Some(("busybox", cmd)) = subcommand {
    37        if cmd.contains_id("install") {
    38            unimplemented!("Make hardlinks to the executable here");
    39        }
    40        subcommand = cmd.subcommand();
    41    }
    42    match subcommand {
    43        Some(("false", _)) => exit(1),
    44        Some(("true", _)) => exit(0),
    45        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    46    }
    47}

More examples
Hide additional examples
examples/derive_ref/hand_subcommand.rs (line 55)

    54    fn augment_subcommands(cmd: Command) -> Command {
    55        cmd.subcommand(AddArgs::augment_args(Command::new("add")))
    56            .subcommand(RemoveArgs::augment_args(Command::new("remove")))
    57            .subcommand_required(true)
    58    }
    59    fn augment_subcommands_for_update(cmd: Command) -> Command {
    60        cmd.subcommand(AddArgs::augment_args(Command::new("add")))
    61            .subcommand(RemoveArgs::augment_args(Command::new("remove")))
    62            .subcommand_required(true)
    63    }

examples/derive_ref/augment_subcommands.rs (line 12)

    11fn main() {
    12    let cli = Command::new("Built CLI");
    13    // Augment with derived subcommands
    14    let cli = Subcommands::augment_subcommands(cli);
    15
    16    let matches = cli.get_matches();
    17    let derived_subcommands = Subcommands::from_arg_matches(&matches)
    18        .map_err(|err| err.exit())
    19        .unwrap();
    20    println!("Derived subcommands: {derived_subcommands:#?}");
    21}

examples/tutorial_builder/02_apps.rs (line 4)

    3fn main() {
    4    let matches = Command::new("MyApp")
    5        .version("1.0")
    6        .about("Does awesome things")
    7        .arg(arg!(--two <VALUE>).required(true))
    8        .arg(arg!(--one <VALUE>).required(true))
    9        .get_matches();
    10
    11    println!(
    12        "two: {:?}",
    13        matches.get_one::<String>("two").expect("required")
    14    );
    15    println!(
    16        "one: {:?}",
    17        matches.get_one::<String>("one").expect("required")
    18    );
    19}

examples/multicall-hostname.rs (line 4)

    3fn main() {
    4    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    5        .multicall(true)
    6        .arg_required_else_help(true)
    7        .subcommand_value_name("APPLET")
    8        .subcommand_help_heading("APPLETS")
    9        .subcommand(Command::new("hostname").about("show hostname part of FQDN"))
    10        .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN"));
    11
    12    match cmd.get_matches().subcommand_name() {
    13        Some("hostname") => println!("www"),
    14        Some("dnsdomainname") => println!("example.com"),
    15        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    16    }
    17}

examples/derive_ref/augment_args.rs (line 10)

    9fn main() {
    10    let cli = Command::new("CLI").arg(arg!(-b - -built).action(clap::ArgAction::SetTrue));
    11    // Augment built args with derived args
    12    let cli = DerivedArgs::augment_args(cli);
    13
    14    let matches = cli.get_matches();
    15    println!("Value of built: {:?}", matches.get_flag("built"));
    16    println!(
    17        "Value of derived via ArgMatches: {:?}",
    18        matches.get_flag("derived")
    19    );
    20
    21    // Since DerivedArgs implements FromArgMatches, we can extract it from the unstructured ArgMatches.
    22    // This is the main benefit of using derived arguments.
    23    let derived_matches = DerivedArgs::from_arg_matches(&matches)
    24        .map_err(|err| err.exit())
    25        .unwrap();
    26    println!("Value of derived: {derived_matches:#?}");
    27}

Additional examples can be found in:

- examples/repl.rs
- examples/git.rs
- examples/pacman.rs

Source

#### pub fn arg(self, a: impl Into<Arg>) -> Command

Adds an argument to the list of valid possibilities.

##### §Examples

    Command::new("myprog")
        // Adding a single "flag" argument with a short and help text, using Arg::new()
        .arg(
            Arg::new("debug")
               .short('d')
               .help("turns on debugging mode")
        )
        // Adding a single "option" argument with a short, a long, and help text using the less
        // verbose Arg::from()
        .arg(
            arg!(-c --config <CONFIG> "Optionally sets a config file to use")
        )

##### Examples found in repository?

examples/tutorial_builder/02_apps.rs (line 7)

    3fn main() {
    4    let matches = Command::new("MyApp")
    5        .version("1.0")
    6        .about("Does awesome things")
    7        .arg(arg!(--two <VALUE>).required(true))
    8        .arg(arg!(--one <VALUE>).required(true))
    9        .get_matches();
    10
    11    println!(
    12        "two: {:?}",
    13        matches.get_one::<String>("two").expect("required")
    14    );
    15    println!(
    16        "one: {:?}",
    17        matches.get_one::<String>("one").expect("required")
    18    );
    19}

More examples
Hide additional examples
examples/derive_ref/flatten_hand_args.rs (lines 39-44)

    38    fn augment_args(cmd: Command) -> Command {
    39        cmd.arg(
    40            Arg::new("foo")
    41                .short('f')
    42                .long("foo")
    43                .action(ArgAction::SetTrue),
    44        )
    45        .arg(
    46            Arg::new("bar")
    47                .short('b')
    48                .long("bar")
    49                .action(ArgAction::SetTrue),
    50        )
    51        .arg(
    52            Arg::new("quuz")
    53                .short('q')
    54                .long("quuz")
    55                .action(ArgAction::Set),
    56        )
    57    }
    58    fn augment_args_for_update(cmd: Command) -> Command {
    59        cmd.arg(
    60            Arg::new("foo")
    61                .short('f')
    62                .long("foo")
    63                .action(ArgAction::SetTrue),
    64        )
    65        .arg(
    66            Arg::new("bar")
    67                .short('b')
    68                .long("bar")
    69                .action(ArgAction::SetTrue),
    70        )
    71        .arg(
    72            Arg::new("quuz")
    73                .short('q')
    74                .long("quuz")
    75                .action(ArgAction::Set),
    76        )
    77    }

examples/derive_ref/augment_args.rs (line 10)

    9fn main() {
    10    let cli = Command::new("CLI").arg(arg!(-b - -built).action(clap::ArgAction::SetTrue));
    11    // Augment built args with derived args
    12    let cli = DerivedArgs::augment_args(cli);
    13
    14    let matches = cli.get_matches();
    15    println!("Value of built: {:?}", matches.get_flag("built"));
    16    println!(
    17        "Value of derived via ArgMatches: {:?}",
    18        matches.get_flag("derived")
    19    );
    20
    21    // Since DerivedArgs implements FromArgMatches, we can extract it from the unstructured ArgMatches.
    22    // This is the main benefit of using derived arguments.
    23    let derived_matches = DerivedArgs::from_arg_matches(&matches)
    24        .map_err(|err| err.exit())
    25        .unwrap();
    26    println!("Value of derived: {derived_matches:#?}");
    27}

examples/multicall-busybox.rs (lines 21-29)

    13fn main() {
    14    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    15        .multicall(true)
    16        .subcommand(
    17            Command::new("busybox")
    18                .arg_required_else_help(true)
    19                .subcommand_value_name("APPLET")
    20                .subcommand_help_heading("APPLETS")
    21                .arg(
    22                    Arg::new("install")
    23                        .long("install")
    24                        .help("Install hardlinks for all subcommands in path")
    25                        .exclusive(true)
    26                        .action(ArgAction::Set)
    27                        .default_missing_value("/usr/local/bin")
    28                        .value_parser(value_parser!(PathBuf)),
    29                )
    30                .subcommands(applet_commands()),
    31        )
    32        .subcommands(applet_commands());
    33
    34    let matches = cmd.get_matches();
    35    let mut subcommand = matches.subcommand();
    36    if let Some(("busybox", cmd)) = subcommand {
    37        if cmd.contains_id("install") {
    38            unimplemented!("Make hardlinks to the executable here");
    39        }
    40        subcommand = cmd.subcommand();
    41    }
    42    match subcommand {
    43        Some(("false", _)) => exit(1),
    44        Some(("true", _)) => exit(0),
    45        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    46    }
    47}

examples/git.rs (line 15)

    6fn cli() -> Command {
    7    Command::new("git")
    8        .about("A fictional versioning CLI")
    9        .subcommand_required(true)
    10        .arg_required_else_help(true)
    11        .allow_external_subcommands(true)
    12        .subcommand(
    13            Command::new("clone")
    14                .about("Clones repos")
    15                .arg(arg!(<REMOTE> "The remote to clone"))
    16                .arg_required_else_help(true),
    17        )
    18        .subcommand(
    19            Command::new("diff")
    20                .about("Compare two commits")
    21                .arg(arg!(base: [COMMIT]))
    22                .arg(arg!(head: [COMMIT]))
    23                .arg(arg!(path: [PATH]).last(true))
    24                .arg(
    25                    arg!(--color <WHEN>)
    26                        .value_parser(["always", "auto", "never"])
    27                        .num_args(0..=1)
    28                        .require_equals(true)
    29                        .default_value("auto")
    30                        .default_missing_value("always"),
    31                ),
    32        )
    33        .subcommand(
    34            Command::new("push")
    35                .about("pushes things")
    36                .arg(arg!(<REMOTE> "The remote to target"))
    37                .arg_required_else_help(true),
    38        )
    39        .subcommand(
    40            Command::new("add")
    41                .about("adds things")
    42                .arg_required_else_help(true)
    43                .arg(arg!(<PATH> ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))),
    44        )
    45        .subcommand(
    46            Command::new("stash")
    47                .args_conflicts_with_subcommands(true)
    48                .flatten_help(true)
    49                .args(push_args())
    50                .subcommand(Command::new("push").args(push_args()))
    51                .subcommand(Command::new("pop").arg(arg!([STASH])))
    52                .subcommand(Command::new("apply").arg(arg!([STASH]))),
    53        )
    54}

examples/pacman.rs (lines 17-25)

    3fn cli() -> Command {
    4    Command::new("pacman")
    5        .about("package manager utility")
    6        .version("5.2.1")
    7        .subcommand_required(true)
    8        .arg_required_else_help(true)
    9        // Query subcommand
    10        //
    11        // Only a few of its arguments are implemented below.
    12        .subcommand(
    13            Command::new("query")
    14                .short_flag('Q')
    15                .long_flag("query")
    16                .about("Query the package database.")
    17                .arg(
    18                    Arg::new("search")
    19                        .short('s')
    20                        .long("search")
    21                        .help("search locally installed packages for matching strings")
    22                        .conflicts_with("info")
    23                        .action(ArgAction::Set)
    24                        .num_args(1..),
    25                )
    26                .arg(
    27                    Arg::new("info")
    28                        .long("info")
    29                        .short('i')
    30                        .conflicts_with("search")
    31                        .help("view package information")
    32                        .action(ArgAction::Set)
    33                        .num_args(1..),
    34                ),
    35        )
    36        // Sync subcommand
    37        //
    38        // Only a few of its arguments are implemented below.
    39        .subcommand(
    40            Command::new("sync")
    41                .short_flag('S')
    42                .long_flag("sync")
    43                .about("Synchronize packages.")
    44                .arg(
    45                    Arg::new("search")
    46                        .short('s')
    47                        .long("search")
    48                        .conflicts_with("info")
    49                        .action(ArgAction::Set)
    50                        .num_args(1..)
    51                        .help("search remote repositories for matching strings"),
    52                )
    53                .arg(
    54                    Arg::new("info")
    55                        .long("info")
    56                        .conflicts_with("search")
    57                        .short('i')
    58                        .action(ArgAction::SetTrue)
    59                        .help("view package information"),
    60                )
    61                .arg(
    62                    Arg::new("package")
    63                        .help("packages")
    64                        .required_unless_present("search")
    65                        .action(ArgAction::Set)
    66                        .num_args(1..),
    67                ),
    68        )
    69}

Source

#### pub fn args(self, args: impl IntoIterator<Item = impl Into<Arg>>) -> Command

Adds multiple arguments to the list of valid possibilities.

##### §Examples

    Command::new("myprog")
        .args([
            arg!(-d --debug "turns on debugging info"),
            Arg::new("input").help("the input file to use")
        ])

##### Examples found in repository?

examples/git.rs (line 49)

    6fn cli() -> Command {
    7    Command::new("git")
    8        .about("A fictional versioning CLI")
    9        .subcommand_required(true)
    10        .arg_required_else_help(true)
    11        .allow_external_subcommands(true)
    12        .subcommand(
    13            Command::new("clone")
    14                .about("Clones repos")
    15                .arg(arg!(<REMOTE> "The remote to clone"))
    16                .arg_required_else_help(true),
    17        )
    18        .subcommand(
    19            Command::new("diff")
    20                .about("Compare two commits")
    21                .arg(arg!(base: [COMMIT]))
    22                .arg(arg!(head: [COMMIT]))
    23                .arg(arg!(path: [PATH]).last(true))
    24                .arg(
    25                    arg!(--color <WHEN>)
    26                        .value_parser(["always", "auto", "never"])
    27                        .num_args(0..=1)
    28                        .require_equals(true)
    29                        .default_value("auto")
    30                        .default_missing_value("always"),
    31                ),
    32        )
    33        .subcommand(
    34            Command::new("push")
    35                .about("pushes things")
    36                .arg(arg!(<REMOTE> "The remote to target"))
    37                .arg_required_else_help(true),
    38        )
    39        .subcommand(
    40            Command::new("add")
    41                .about("adds things")
    42                .arg_required_else_help(true)
    43                .arg(arg!(<PATH> ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))),
    44        )
    45        .subcommand(
    46            Command::new("stash")
    47                .args_conflicts_with_subcommands(true)
    48                .flatten_help(true)
    49                .args(push_args())
    50                .subcommand(Command::new("push").args(push_args()))
    51                .subcommand(Command::new("pop").arg(arg!([STASH])))
    52                .subcommand(Command::new("apply").arg(arg!([STASH]))),
    53        )
    54}

Source

#### pub fn mut_arg<F>(self, arg_id: impl AsRef<str>, f: F) -> Command
where F: FnOnce(Arg) -> Arg,

Allows one to mutate an `Arg` after it’s been added to a `Command`.

##### §Panics

If the argument is undefined

##### §Examples

    let mut cmd = Command::new("foo")
        .arg(Arg::new("bar")
            .short('b')
            .action(ArgAction::SetTrue))
        .mut_arg("bar", |a| a.short('B'));

    let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]);

    // Since we changed `bar`'s short to "B" this should err as there
    // is no `-b` anymore, only `-B`

    assert!(res.is_err());

    let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]);
    assert!(res.is_ok());

Source

#### pub fn mut_args<F>(self, f: F) -> Command
where F: FnMut(Arg) -> Arg,

Allows one to mutate all `Arg`s after they’ve been added to a `Command`.

This does not affect the built-in `--help` or `--version` arguments.

##### §Examples

    let mut cmd = Command::new("foo")
        .arg(Arg::new("bar")
            .long("bar")
            .action(ArgAction::SetTrue))
        .arg(Arg::new("baz")
            .long("baz")
            .action(ArgAction::SetTrue))
        .mut_args(|a| {
            if let Some(l) = a.get_long().map(|l| format!("prefix-{l}")) {
                a.long(l)
            } else {
                a
            }
        });

    let res = cmd.try_get_matches_from_mut(vec!["foo", "--bar"]);

    // Since we changed `bar`'s long to "prefix-bar" this should err as there
    // is no `--bar` anymore, only `--prefix-bar`.

    assert!(res.is_err());

    let res = cmd.try_get_matches_from_mut(vec!["foo", "--prefix-bar"]);
    assert!(res.is_ok());

Source

#### pub fn mut_group<F>(self, arg_id: impl AsRef<str>, f: F) -> Command
where F: FnOnce(ArgGroup) -> ArgGroup,

Allows one to mutate an `ArgGroup` after it’s been added to a `Command`.

##### §Panics

If the argument is undefined

##### §Examples

    Command::new("foo")
        .arg(arg!(--"set-ver" <ver> "set the version manually").required(false))
        .arg(arg!(--major "auto increase major"))
        .arg(arg!(--minor "auto increase minor"))
        .arg(arg!(--patch "auto increase patch"))
        .group(ArgGroup::new("vers")
             .args(["set-ver", "major", "minor","patch"])
             .required(true))
        .mut_group("vers", |a| a.required(false));

Source

#### pub fn mut_subcommand<F>(self, name: impl AsRef<str>, f: F) -> Command
where F: FnOnce(Command) -> Command,

Allows one to mutate a `Command` after it’s been added as a subcommand.

This can be useful for modifying auto-generated arguments of nested subcommands with `Command::mut_arg`.

##### §Panics

If the subcommand is undefined

##### §Examples

    let mut cmd = Command::new("foo")
            .subcommand(Command::new("bar"))
            .mut_subcommand("bar", |subcmd| subcmd.disable_help_flag(true));

    let res = cmd.try_get_matches_from_mut(vec!["foo", "bar", "--help"]);

    // Since we disabled the help flag on the "bar" subcommand, this should err.

    assert!(res.is_err());

    let res = cmd.try_get_matches_from_mut(vec!["foo", "bar"]);
    assert!(res.is_ok());

Source

#### pub fn mut_subcommands<F>(self, f: F) -> Command
where F: FnMut(Command) -> Command,

Allows one to mutate all `Command`s after they’ve been added as subcommands.

This does not affect the built-in `--help` or `--version` arguments.

##### §Examples

    let mut cmd = Command::new("foo")
        .subcommands([
            Command::new("fetch"),
            Command::new("push"),
        ])
        // Allow title-case subcommands
        .mut_subcommands(|sub| {
            let name = sub.get_name();
            let alias = name.chars().enumerate().map(|(i, c)| {
                if i == 0 {
                    c.to_ascii_uppercase()
                } else {
                    c
                }
            }).collect::<String>();
            sub.alias(alias)
        });

    let res = cmd.try_get_matches_from_mut(vec!["foo", "fetch"]);
    assert!(res.is_ok());

    let res = cmd.try_get_matches_from_mut(vec!["foo", "Fetch"]);
    assert!(res.is_ok());

Source

#### pub fn group(self, group: impl Into<ArgGroup>) -> Command

Adds an `ArgGroup` to the application.

`ArgGroup`s are a family of related arguments. By placing them in a logical group, you can build easier requirement and exclusion rules.

Example use cases:

- Make an entire `ArgGroup` required, meaning that one (and only one) argument from that group must be present at runtime.
- Name an `ArgGroup` as a conflict to another argument. Meaning any of the arguments that belong to that group will cause a failure if present with the conflicting argument.
- Ensure exclusion between arguments.
- Extract a value from a group instead of determining exactly which argument was used.

##### §Examples

The following example demonstrates using an `ArgGroup` to ensure that one, and only one, of the arguments from the specified group is present at runtime.

    Command::new("cmd")
        .arg(arg!(--"set-ver" <ver> "set the version manually").required(false))
        .arg(arg!(--major "auto increase major"))
        .arg(arg!(--minor "auto increase minor"))
        .arg(arg!(--patch "auto increase patch"))
        .group(ArgGroup::new("vers")
             .args(["set-ver", "major", "minor","patch"])
             .required(true))

Source

#### pub fn groups( self, groups: impl IntoIterator<Item = impl Into<ArgGroup>>, ) -> Command

Adds multiple `ArgGroup`s to the `Command` at once.

##### §Examples

    Command::new("cmd")
        .arg(arg!(--"set-ver" <ver> "set the version manually").required(false))
        .arg(arg!(--major         "auto increase major"))
        .arg(arg!(--minor         "auto increase minor"))
        .arg(arg!(--patch         "auto increase patch"))
        .arg(arg!(-c <FILE>       "a config file").required(false))
        .arg(arg!(-i <IFACE>      "an interface").required(false))
        .groups([
            ArgGroup::new("vers")
                .args(["set-ver", "major", "minor","patch"])
                .required(true),
            ArgGroup::new("input")
                .args(["c", "i"])
        ])

Source

#### pub fn subcommand(self, subcmd: impl Into<Command>) -> Command

Adds a subcommand to the list of valid possibilities.

Subcommands are effectively sub-`Command`s, because they can contain their own arguments, subcommands, version, usage, etc. They also function just like `Command`s, in that they get their own auto generated help, version, and usage.

A subcommand’s `Command::name` will be used for:

- The argument the user passes in
- Programmatically looking up the subcommand

##### §Examples

    Command::new("myprog")
        .subcommand(Command::new("config")
            .about("Controls configuration features")
            .arg(arg!(<config> "Required configuration file to use")))

##### Examples found in repository?

examples/derive_ref/hand_subcommand.rs (line 55)

    54    fn augment_subcommands(cmd: Command) -> Command {
    55        cmd.subcommand(AddArgs::augment_args(Command::new("add")))
    56            .subcommand(RemoveArgs::augment_args(Command::new("remove")))
    57            .subcommand_required(true)
    58    }
    59    fn augment_subcommands_for_update(cmd: Command) -> Command {
    60        cmd.subcommand(AddArgs::augment_args(Command::new("add")))
    61            .subcommand(RemoveArgs::augment_args(Command::new("remove")))
    62            .subcommand_required(true)
    63    }

More examples
Hide additional examples
examples/multicall-hostname.rs (line 9)

    3fn main() {
    4    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    5        .multicall(true)
    6        .arg_required_else_help(true)
    7        .subcommand_value_name("APPLET")
    8        .subcommand_help_heading("APPLETS")
    9        .subcommand(Command::new("hostname").about("show hostname part of FQDN"))
    10        .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN"));
    11
    12    match cmd.get_matches().subcommand_name() {
    13        Some("hostname") => println!("www"),
    14        Some("dnsdomainname") => println!("example.com"),
    15        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    16    }
    17}

examples/repl.rs (lines 71-75)

    51fn cli() -> Command {
    52    // strip out usage
    53    const PARSER_TEMPLATE: &str = "\
    54        {all-args}
    55    ";
    56    // strip out name/version
    57    const APPLET_TEMPLATE: &str = "\
    58        {about-with-newline}\n\
    59        {usage-heading}\n    {usage}\n\
    60        \n\
    61        {all-args}{after-help}\
    62    ";
    63
    64    Command::new("repl")
    65        .multicall(true)
    66        .arg_required_else_help(true)
    67        .subcommand_required(true)
    68        .subcommand_value_name("APPLET")
    69        .subcommand_help_heading("APPLETS")
    70        .help_template(PARSER_TEMPLATE)
    71        .subcommand(
    72            Command::new("ping")
    73                .about("Get a response")
    74                .help_template(APPLET_TEMPLATE),
    75        )
    76        .subcommand(
    77            Command::new("quit")
    78                .alias("exit")
    79                .about("Quit the REPL")
    80                .help_template(APPLET_TEMPLATE),
    81        )
    82}

examples/multicall-busybox.rs (lines 16-31)

    13fn main() {
    14    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    15        .multicall(true)
    16        .subcommand(
    17            Command::new("busybox")
    18                .arg_required_else_help(true)
    19                .subcommand_value_name("APPLET")
    20                .subcommand_help_heading("APPLETS")
    21                .arg(
    22                    Arg::new("install")
    23                        .long("install")
    24                        .help("Install hardlinks for all subcommands in path")
    25                        .exclusive(true)
    26                        .action(ArgAction::Set)
    27                        .default_missing_value("/usr/local/bin")
    28                        .value_parser(value_parser!(PathBuf)),
    29                )
    30                .subcommands(applet_commands()),
    31        )
    32        .subcommands(applet_commands());
    33
    34    let matches = cmd.get_matches();
    35    let mut subcommand = matches.subcommand();
    36    if let Some(("busybox", cmd)) = subcommand {
    37        if cmd.contains_id("install") {
    38            unimplemented!("Make hardlinks to the executable here");
    39        }
    40        subcommand = cmd.subcommand();
    41    }
    42    match subcommand {
    43        Some(("false", _)) => exit(1),
    44        Some(("true", _)) => exit(0),
    45        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    46    }
    47}

examples/git.rs (lines 12-17)

    6fn cli() -> Command {
    7    Command::new("git")
    8        .about("A fictional versioning CLI")
    9        .subcommand_required(true)
    10        .arg_required_else_help(true)
    11        .allow_external_subcommands(true)
    12        .subcommand(
    13            Command::new("clone")
    14                .about("Clones repos")
    15                .arg(arg!(<REMOTE> "The remote to clone"))
    16                .arg_required_else_help(true),
    17        )
    18        .subcommand(
    19            Command::new("diff")
    20                .about("Compare two commits")
    21                .arg(arg!(base: [COMMIT]))
    22                .arg(arg!(head: [COMMIT]))
    23                .arg(arg!(path: [PATH]).last(true))
    24                .arg(
    25                    arg!(--color <WHEN>)
    26                        .value_parser(["always", "auto", "never"])
    27                        .num_args(0..=1)
    28                        .require_equals(true)
    29                        .default_value("auto")
    30                        .default_missing_value("always"),
    31                ),
    32        )
    33        .subcommand(
    34            Command::new("push")
    35                .about("pushes things")
    36                .arg(arg!(<REMOTE> "The remote to target"))
    37                .arg_required_else_help(true),
    38        )
    39        .subcommand(
    40            Command::new("add")
    41                .about("adds things")
    42                .arg_required_else_help(true)
    43                .arg(arg!(<PATH> ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))),
    44        )
    45        .subcommand(
    46            Command::new("stash")
    47                .args_conflicts_with_subcommands(true)
    48                .flatten_help(true)
    49                .args(push_args())
    50                .subcommand(Command::new("push").args(push_args()))
    51                .subcommand(Command::new("pop").arg(arg!([STASH])))
    52                .subcommand(Command::new("apply").arg(arg!([STASH]))),
    53        )
    54}

examples/pacman.rs (lines 12-35)

    3fn cli() -> Command {
    4    Command::new("pacman")
    5        .about("package manager utility")
    6        .version("5.2.1")
    7        .subcommand_required(true)
    8        .arg_required_else_help(true)
    9        // Query subcommand
    10        //
    11        // Only a few of its arguments are implemented below.
    12        .subcommand(
    13            Command::new("query")
    14                .short_flag('Q')
    15                .long_flag("query")
    16                .about("Query the package database.")
    17                .arg(
    18                    Arg::new("search")
    19                        .short('s')
    20                        .long("search")
    21                        .help("search locally installed packages for matching strings")
    22                        .conflicts_with("info")
    23                        .action(ArgAction::Set)
    24                        .num_args(1..),
    25                )
    26                .arg(
    27                    Arg::new("info")
    28                        .long("info")
    29                        .short('i')
    30                        .conflicts_with("search")
    31                        .help("view package information")
    32                        .action(ArgAction::Set)
    33                        .num_args(1..),
    34                ),
    35        )
    36        // Sync subcommand
    37        //
    38        // Only a few of its arguments are implemented below.
    39        .subcommand(
    40            Command::new("sync")
    41                .short_flag('S')
    42                .long_flag("sync")
    43                .about("Synchronize packages.")
    44                .arg(
    45                    Arg::new("search")
    46                        .short('s')
    47                        .long("search")
    48                        .conflicts_with("info")
    49                        .action(ArgAction::Set)
    50                        .num_args(1..)
    51                        .help("search remote repositories for matching strings"),
    52                )
    53                .arg(
    54                    Arg::new("info")
    55                        .long("info")
    56                        .conflicts_with("search")
    57                        .short('i')
    58                        .action(ArgAction::SetTrue)
    59                        .help("view package information"),
    60                )
    61                .arg(
    62                    Arg::new("package")
    63                        .help("packages")
    64                        .required_unless_present("search")
    65                        .action(ArgAction::Set)
    66                        .num_args(1..),
    67                ),
    68        )
    69}

Source

#### pub fn subcommands( self, subcmds: impl IntoIterator<Item = impl Into<Command>>, ) -> Command

Adds multiple subcommands to the list of valid possibilities.

##### §Examples

    .subcommands( [
           Command::new("config").about("Controls configuration functionality")
                                    .arg(Arg::new("config_file")),
           Command::new("debug").about("Controls debug functionality")])

##### Examples found in repository?

examples/multicall-busybox.rs (line 30)

    13fn main() {
    14    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    15        .multicall(true)
    16        .subcommand(
    17            Command::new("busybox")
    18                .arg_required_else_help(true)
    19                .subcommand_value_name("APPLET")
    20                .subcommand_help_heading("APPLETS")
    21                .arg(
    22                    Arg::new("install")
    23                        .long("install")
    24                        .help("Install hardlinks for all subcommands in path")
    25                        .exclusive(true)
    26                        .action(ArgAction::Set)
    27                        .default_missing_value("/usr/local/bin")
    28                        .value_parser(value_parser!(PathBuf)),
    29                )
    30                .subcommands(applet_commands()),
    31        )
    32        .subcommands(applet_commands());
    33
    34    let matches = cmd.get_matches();
    35    let mut subcommand = matches.subcommand();
    36    if let Some(("busybox", cmd)) = subcommand {
    37        if cmd.contains_id("install") {
    38            unimplemented!("Make hardlinks to the executable here");
    39        }
    40        subcommand = cmd.subcommand();
    41    }
    42    match subcommand {
    43        Some(("false", _)) => exit(1),
    44        Some(("true", _)) => exit(0),
    45        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    46    }
    47}

Source

#### pub fn defer(self, deferred: fn(Command) -> Command) -> Command

Delay initialization for parts of the `Command`

This is useful for large applications to delay definitions of subcommands until they are being invoked.

##### §Examples

    Command::new("myprog")
        .subcommand(Command::new("config")
            .about("Controls configuration features")
            .defer(|cmd| {
                cmd.arg(arg!(<config> "Required configuration file to use"))
            })
        )

Source

#### pub fn debug_assert(self)

Catch problems earlier in the development cycle.

Most error states are handled as asserts under the assumption they are programming mistake and not something to handle at runtime. Rather than relying on tests (manual or automated) that exhaustively test your CLI to ensure the asserts are evaluated, this will run those asserts in a way convenient for running as a test.

Note: This will not help with asserts in `ArgMatches`, those will need exhaustive testing of your CLI.

##### §Examples

    fn cmd() -> Command {
        Command::new("foo")
            .arg(
                Arg::new("bar").short('b').action(ArgAction::SetTrue)
            )
    }

    #[test]
    fn verify_app() {
        cmd().debug_assert();
    }

    let m = cmd().get_matches_from(vec!["foo", "-b"]);
    println!("{}", m.get_flag("bar"));

Source

#### pub fn error(&mut self, kind: ErrorKind, message: impl Display) -> Error

Custom error message for post-parsing validation

Note: this will ensure the `Command` has been sufficiently built for any relevant context, including usage.

##### §Panics

If contradictory arguments or settings exist (debug builds).

##### §Examples

    let mut cmd = Command::new("myprog");
    let err = cmd.error(ErrorKind::InvalidValue, "Some failure case");

##### Examples found in repository?

examples/tutorial_derive/04_04_custom.rs (lines 46-49)

    34fn main() {
    35    let cli = Cli::parse();
    36
    37    // Let's assume the old version 1.2.3
    38    let mut major = 1;
    39    let mut minor = 2;
    40    let mut patch = 3;
    41
    42    // See if --set-ver was used to set the version manually
    43    let version = if let Some(ver) = cli.set_ver.as_deref() {
    44        if cli.major || cli.minor || cli.patch {
    45            let mut cmd = Cli::command();
    46            cmd.error(
    47                ErrorKind::ArgumentConflict,
    48                "Can't do relative and absolute version change",
    49            )
    50            .exit();
    51        }
    52        ver.to_owned()
    53    } else {
    54        // Increment the one requested (in a real program, we'd reset the lower numbers)
    55        let (maj, min, pat) = (cli.major, cli.minor, cli.patch);
    56        match (maj, min, pat) {
    57            (true, false, false) => major += 1,
    58            (false, true, false) => minor += 1,
    59            (false, false, true) => patch += 1,
    60            _ => {
    61                let mut cmd = Cli::command();
    62                cmd.error(
    63                    ErrorKind::ArgumentConflict,
    64                    "Can only modify one version field",
    65                )
    66                .exit();
    67            }
    68        };
    69        format!("{major}.{minor}.{patch}")
    70    };
    71
    72    println!("Version: {version}");
    73
    74    // Check for usage of -c
    75    if let Some(config) = cli.config.as_deref() {
    76        let input = cli
    77            .input_file
    78            .as_deref()
    79            // 'or' is preferred to 'or_else' here since `Option::as_deref` is 'const'
    80            .or(cli.spec_in.as_deref())
    81            .unwrap_or_else(|| {
    82                let mut cmd = Cli::command();
    83                cmd.error(
    84                    ErrorKind::MissingRequiredArgument,
    85                    "INPUT_FILE or --spec-in is required when using --config",
    86                )
    87                .exit()
    88            });
    89        println!("Doing work using input {input} and config {config}");
    90    }
    91}

Source

#### pub fn get_matches(self) -> ArgMatches

Parse `env::args_os`, exiting on failure.

##### §Panics

If contradictory arguments or settings exist (debug builds).

##### §Examples

    let matches = Command::new("myprog")
        // Args and options go here...
        .get_matches();

##### Examples found in repository?

examples/derive_ref/augment_subcommands.rs (line 16)

    11fn main() {
    12    let cli = Command::new("Built CLI");
    13    // Augment with derived subcommands
    14    let cli = Subcommands::augment_subcommands(cli);
    15
    16    let matches = cli.get_matches();
    17    let derived_subcommands = Subcommands::from_arg_matches(&matches)
    18        .map_err(|err| err.exit())
    19        .unwrap();
    20    println!("Derived subcommands: {derived_subcommands:#?}");
    21}

More examples
Hide additional examples
examples/tutorial_builder/02_apps.rs (line 9)

    3fn main() {
    4    let matches = Command::new("MyApp")
    5        .version("1.0")
    6        .about("Does awesome things")
    7        .arg(arg!(--two <VALUE>).required(true))
    8        .arg(arg!(--one <VALUE>).required(true))
    9        .get_matches();
    10
    11    println!(
    12        "two: {:?}",
    13        matches.get_one::<String>("two").expect("required")
    14    );
    15    println!(
    16        "one: {:?}",
    17        matches.get_one::<String>("one").expect("required")
    18    );
    19}

examples/multicall-hostname.rs (line 12)

    3fn main() {
    4    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    5        .multicall(true)
    6        .arg_required_else_help(true)
    7        .subcommand_value_name("APPLET")
    8        .subcommand_help_heading("APPLETS")
    9        .subcommand(Command::new("hostname").about("show hostname part of FQDN"))
    10        .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN"));
    11
    12    match cmd.get_matches().subcommand_name() {
    13        Some("hostname") => println!("www"),
    14        Some("dnsdomainname") => println!("example.com"),
    15        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    16    }
    17}

examples/derive_ref/augment_args.rs (line 14)

    9fn main() {
    10    let cli = Command::new("CLI").arg(arg!(-b - -built).action(clap::ArgAction::SetTrue));
    11    // Augment built args with derived args
    12    let cli = DerivedArgs::augment_args(cli);
    13
    14    let matches = cli.get_matches();
    15    println!("Value of built: {:?}", matches.get_flag("built"));
    16    println!(
    17        "Value of derived via ArgMatches: {:?}",
    18        matches.get_flag("derived")
    19    );
    20
    21    // Since DerivedArgs implements FromArgMatches, we can extract it from the unstructured ArgMatches.
    22    // This is the main benefit of using derived arguments.
    23    let derived_matches = DerivedArgs::from_arg_matches(&matches)
    24        .map_err(|err| err.exit())
    25        .unwrap();
    26    println!("Value of derived: {derived_matches:#?}");
    27}

examples/multicall-busybox.rs (line 34)

    13fn main() {
    14    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    15        .multicall(true)
    16        .subcommand(
    17            Command::new("busybox")
    18                .arg_required_else_help(true)
    19                .subcommand_value_name("APPLET")
    20                .subcommand_help_heading("APPLETS")
    21                .arg(
    22                    Arg::new("install")
    23                        .long("install")
    24                        .help("Install hardlinks for all subcommands in path")
    25                        .exclusive(true)
    26                        .action(ArgAction::Set)
    27                        .default_missing_value("/usr/local/bin")
    28                        .value_parser(value_parser!(PathBuf)),
    29                )
    30                .subcommands(applet_commands()),
    31        )
    32        .subcommands(applet_commands());
    33
    34    let matches = cmd.get_matches();
    35    let mut subcommand = matches.subcommand();
    36    if let Some(("busybox", cmd)) = subcommand {
    37        if cmd.contains_id("install") {
    38            unimplemented!("Make hardlinks to the executable here");
    39        }
    40        subcommand = cmd.subcommand();
    41    }
    42    match subcommand {
    43        Some(("false", _)) => exit(1),
    44        Some(("true", _)) => exit(0),
    45        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    46    }
    47}

examples/pacman.rs (line 72)

    71fn main() {
    72    let matches = cli().get_matches();
    73
    74    match matches.subcommand() {
    75        Some(("sync", sync_matches)) => {
    76            if sync_matches.contains_id("search") {
    77                let packages: Vec<_> = sync_matches
    78                    .get_many::<String>("search")
    79                    .expect("contains_id")
    80                    .map(|s| s.as_str())
    81                    .collect();
    82                let values = packages.join(", ");
    83                println!("Searching for {values}...");
    84                return;
    85            }
    86
    87            let packages: Vec<_> = sync_matches
    88                .get_many::<String>("package")
    89                .expect("is present")
    90                .map(|s| s.as_str())
    91                .collect();
    92            let values = packages.join(", ");
    93
    94            if sync_matches.get_flag("info") {
    95                println!("Retrieving info for {values}...");
    96            } else {
    97                println!("Installing {values}...");
    98            }
    99        }
    100        Some(("query", query_matches)) => {
    101            if let Some(packages) = query_matches.get_many::<String>("info") {
    102                let comma_sep = packages.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
    103                println!("Retrieving info for {comma_sep}...");
    104            } else if let Some(queries) = query_matches.get_many::<String>("search") {
    105                let comma_sep = queries.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
    106                println!("Searching Locally for {comma_sep}...");
    107            } else {
    108                println!("Displaying all locally installed packages...");
    109            }
    110        }
    111        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
    112    }
    113}

Additional examples can be found in:

- examples/git.rs

Source

#### pub fn get_matches_mut(&mut self) -> ArgMatches

Parse `env::args_os`, exiting on failure.

Like `Command::get_matches` but doesn’t consume the `Command`.

##### §Panics

If contradictory arguments or settings exist (debug builds).

##### §Examples

    let mut cmd = Command::new("myprog")
        // Args and options go here...
        ;
    let matches = cmd.get_matches_mut();

Source

#### pub fn try_get_matches(self) -> Result<ArgMatches, Error>

Parse `env::args_os`, returning a `clap::Result` on failure.

NOTE: This method WILL NOT exit when `--help` or `--version` (or short versions) are used. It will return a `clap::Error`, where the `kind` is a `ErrorKind::DisplayHelp` or `ErrorKind::DisplayVersion` respectively. You must call `Error::exit` or perform a `std::process::exit`.

##### §Panics

If contradictory arguments or settings exist (debug builds).

##### §Examples

    let matches = Command::new("myprog")
        // Args and options go here...
        .try_get_matches()
        .unwrap_or_else(|e| e.exit());

Source

#### pub fn get_matches_from<I, T>(self, itr: I) -> ArgMatches
where I: IntoIterator<Item = T>, T: Into<OsString> + Clone,

Parse the specified arguments, exiting on failure.

NOTE: The first argument will be parsed as the binary name unless `Command::no_binary_name` is used.

##### §Panics

If contradictory arguments or settings exist (debug builds).

##### §Examples

    let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];

    let matches = Command::new("myprog")
        // Args and options go here...
        .get_matches_from(arg_vec);

Source

#### pub fn try_get_matches_from<I, T>(self, itr: I) -> Result<ArgMatches, Error>
where I: IntoIterator<Item = T>, T: Into<OsString> + Clone,

Parse the specified arguments, returning a `clap::Result` on failure.

NOTE: This method WILL NOT exit when `--help` or `--version` (or short versions) are used. It will return a `clap::Error`, where the `kind` is a `ErrorKind::DisplayHelp` or `ErrorKind::DisplayVersion` respectively. You must call `Error::exit` or perform a `std::process::exit` yourself.

NOTE: The first argument will be parsed as the binary name unless `Command::no_binary_name` is used.

##### §Panics

If contradictory arguments or settings exist (debug builds).

##### §Examples

    let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];

    let matches = Command::new("myprog")
        // Args and options go here...
        .try_get_matches_from(arg_vec)
        .unwrap_or_else(|e| e.exit());

##### Examples found in repository?

examples/repl.rs (line 32)

    29fn respond(line: &str) -> Result<bool, String> {
    30    let args = shlex::split(line).ok_or("error: Invalid quoting")?;
    31    let matches = cli()
    32        .try_get_matches_from(args)
    33        .map_err(|e| e.to_string())?;
    34    match matches.subcommand() {
    35        Some(("ping", _matches)) => {
    36            write!(std::io::stdout(), "Pong").map_err(|e| e.to_string())?;
    37            std::io::stdout().flush().map_err(|e| e.to_string())?;
    38        }
    39        Some(("quit", _matches)) => {
    40            write!(std::io::stdout(), "Exiting ...").map_err(|e| e.to_string())?;
    41            std::io::stdout().flush().map_err(|e| e.to_string())?;
    42            return Ok(true);
    43        }
    44        Some((name, _matches)) => unimplemented!("{name}"),
    45        None => unreachable!("subcommand required"),
    46    }
    47
    48    Ok(false)
    49}

Source

#### pub fn try_get_matches_from_mut<I, T>( &mut self, itr: I, ) -> Result<ArgMatches, Error>
where I: IntoIterator<Item = T>, T: Into<OsString> + Clone,

Parse the specified arguments, returning a `clap::Result` on failure.

Like `Command::try_get_matches_from` but doesn’t consume the `Command`.

NOTE: This method WILL NOT exit when `--help` or `--version` (or short versions) are used. It will return a `clap::Error`, where the `kind` is a `ErrorKind::DisplayHelp` or `ErrorKind::DisplayVersion` respectively. You must call `Error::exit` or perform a `std::process::exit` yourself.

NOTE: The first argument will be parsed as the binary name unless `Command::no_binary_name` is used.

##### §Panics

If contradictory arguments or settings exist (debug builds).

##### §Examples

    let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];

    let mut cmd = Command::new("myprog");
        // Args and options go here...
    let matches = cmd.try_get_matches_from_mut(arg_vec)
        .unwrap_or_else(|e| e.exit());

Source

#### pub fn print_help(&mut self) -> Result<(), Error>

Prints the short help message (`-h`) to `io::stdout()`.

See also `Command::print_long_help`.

Note: this will ensure the `Command` has been sufficiently built.

##### §Panics

If contradictory arguments or settings exist (debug builds).

##### §Examples

    let mut cmd = Command::new("myprog");
    cmd.print_help();

Source

#### pub fn print_long_help(&mut self) -> Result<(), Error>

Prints the long help message (`--help`) to `io::stdout()`.

See also `Command::print_help`.

Note: this will ensure the `Command` has been sufficiently built.

##### §Panics

If contradictory arguments or settings exist (debug builds).

##### §Examples

    let mut cmd = Command::new("myprog");
    cmd.print_long_help();

Source

#### pub fn render_help(&mut self) -> StyledStr

Render the short help message (`-h`) to a `StyledStr`

See also `Command::render_long_help`.

Note: this will ensure the `Command` has been sufficiently built.

##### §Panics

If contradictory arguments or settings exist (debug builds).

##### §Examples

    use std::io;
    let mut cmd = Command::new("myprog");
    let mut out = io::stdout();
    let help = cmd.render_help();
    println!("{help}");

Source

#### pub fn render_long_help(&mut self) -> StyledStr

Render the long help message (`--help`) to a `StyledStr`.

See also `Command::render_help`.

Note: this will ensure the `Command` has been sufficiently built.

##### §Panics

If contradictory arguments or settings exist (debug builds).

##### §Examples

    use std::io;
    let mut cmd = Command::new("myprog");
    let mut out = io::stdout();
    let help = cmd.render_long_help();
    println!("{help}");

Source

#### pub fn render_version(&self) -> String

Version message rendered as if the user ran `-V`.

See also `Command::render_long_version`.

###### §Coloring

This function does not try to color the message nor it inserts any ANSI escape codes.

###### §Examples

    use std::io;
    let cmd = Command::new("myprog");
    println!("{}", cmd.render_version());

Source

#### pub fn render_long_version(&self) -> String

Version message rendered as if the user ran `--version`.

See also `Command::render_version`.

###### §Coloring

This function does not try to color the message nor it inserts any ANSI escape codes.

###### §Examples

    use std::io;
    let cmd = Command::new("myprog");
    println!("{}", cmd.render_long_version());

Source

#### pub fn render_usage(&mut self) -> StyledStr

Usage statement

Note: this will ensure the `Command` has been sufficiently built.

##### §Panics

If contradictory arguments or settings exist (debug builds).

###### §Examples

    use std::io;
    let mut cmd = Command::new("myprog");
    println!("{}", cmd.render_usage());

Source

#### pub fn add<T>(self, tagged: T) -> Command
where T: CommandExt + Extension,

Available on crate feature `unstable-ext` only.

Extend `Command` with `CommandExt` data

Source§

### impl Command

#### §Application-wide Settings

These settings will apply to the top-level command and all subcommands, by default. Some settings can be overridden in subcommands.

Source

#### pub fn no_binary_name(self, yes: bool) -> Command

Specifies that the parser should not assume the first argument passed is the binary name.

This is normally the case when using a “daemon” style mode. For shells / REPLs, see `Command::multicall`.

##### §Examples

    let m = Command::new("myprog")
        .no_binary_name(true)
        .arg(arg!(<cmd> ... "commands to run"))
        .get_matches_from(vec!["command", "set"]);

    let cmds: Vec<_> = m.get_many::<String>("cmd").unwrap().collect();
    assert_eq!(cmds, ["command", "set"]);

Source

#### pub fn ignore_errors(self, yes: bool) -> Command

Try not to fail on parse errors, like missing option values.

NOTE: This choice is propagated to all child subcommands.

##### §Examples

    let cmd = Command::new("cmd")
      .ignore_errors(true)
      .arg(arg!(-c --config <FILE> "Sets a custom config file"))
      .arg(arg!(-x --stuff <FILE> "Sets a custom stuff file"))
      .arg(arg!(f: -f "Flag"));

    let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]);

    assert!(r.is_ok(), "unexpected error: {r:?}");
    let m = r.unwrap();
    assert_eq!(m.get_one::<String>("config").unwrap(), "file");
    assert!(m.get_flag("f"));
    assert_eq!(m.get_one::<String>("stuff"), None);

Source

#### pub fn args_override_self(self, yes: bool) -> Command

Replace prior occurrences of arguments rather than error

For any argument that would conflict with itself by default (e.g. `ArgAction::Set`, it will now override itself.

This is the equivalent to saying the `foo` arg using `Arg::overrides_with("foo")` for all defined arguments.

NOTE: This choice is propagated to all child subcommands.

Source

#### pub fn dont_delimit_trailing_values(self, yes: bool) -> Command

Disables the automatic delimiting of values after `--` or when `Arg::trailing_var_arg` was used.

NOTE: The same thing can be done manually by setting the final positional argument to `Arg::value_delimiter(None)`. Using this setting is safer, because it’s easier to locate when making changes.

NOTE: This choice is propagated to all child subcommands.

##### §Examples

    Command::new("myprog")
        .dont_delimit_trailing_values(true)
        .get_matches();

Source

#### pub fn color(self, color: ColorChoice) -> Command

Available on crate feature `color` only.

Sets when to color output.

To customize how the output is styled, see `Command::styles`.

NOTE: This choice is propagated to all child subcommands.

NOTE: Default behaviour is `ColorChoice::Auto`.

##### §Examples

    Command::new("myprog")
        .color(ColorChoice::Never)
        .get_matches();

Source

#### pub fn styles(self, styles: Styles) -> Command

Available on crate feature `color` only.

Sets the `Styles` for terminal output

NOTE: This choice is propagated to all child subcommands.

NOTE: Default behaviour is `Styles::default`.

##### §Examples

    const STYLES: styling::Styles = styling::Styles::styled()
        .header(styling::AnsiColor::Green.on_default().bold())
        .usage(styling::AnsiColor::Green.on_default().bold())
        .literal(styling::AnsiColor::Blue.on_default().bold())
        .placeholder(styling::AnsiColor::Cyan.on_default());
    Command::new("myprog")
        .styles(STYLES)
        .get_matches();

Source

#### pub fn term_width(self, width: usize) -> Command

Available on crate feature `wrap_help` or non-crate feature `unstable-v5` only.

Sets the terminal width at which to wrap help messages.

Using `0` will ignore terminal widths and use source formatting.

Defaults to current terminal width when `wrap_help` feature flag is enabled. If current width cannot be determined, the default is 100.

`unstable-v5` feature: Defaults to unbound, being subject to `Command::max_term_width`.

NOTE: This setting applies globally and not on a per-command basis.

NOTE: This requires the `wrap_help` feature

##### §Examples

    Command::new("myprog")
        .term_width(80)

Source

#### pub fn max_term_width(self, width: usize) -> Command

Available on crate feature `wrap_help` or non-crate feature `unstable-v5` only.

Limit the line length for wrapping help when using the current terminal’s width.

This only applies when `term_width` is unset so that the current terminal’s width will be used. See `Command::term_width` for more details.

Using `0` will ignore this, always respecting `Command::term_width` (default).

`unstable-v5` feature: Defaults to 100.

NOTE: This setting applies globally and not on a per-command basis.

NOTE: This requires the `wrap_help` feature

##### §Examples

    Command::new("myprog")
        .max_term_width(100)

Source

#### pub fn disable_version_flag(self, yes: bool) -> Command

Disables `-V` and `--version` flag.

##### §Examples

    let res = Command::new("myprog")
        .version("1.0.0")
        .disable_version_flag(true)
        .try_get_matches_from(vec![
            "myprog", "--version"
        ]);
    assert!(res.is_err());
    assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);

You can create a custom version flag with `ArgAction::Version`

    let mut cmd = Command::new("myprog")
        .version("1.0.0")
        // Remove the `-V` short flag
        .disable_version_flag(true)
        .arg(
            Arg::new("version")
                .long("version")
                .action(ArgAction::Version)
                .help("Print version")
        );

    let res = cmd.try_get_matches_from_mut(vec![
            "myprog", "-V"
        ]);
    assert!(res.is_err());
    assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);

    let res = cmd.try_get_matches_from_mut(vec![
            "myprog", "--version"
        ]);
    assert!(res.is_err());
    assert_eq!(res.unwrap_err().kind(), ErrorKind::DisplayVersion);

Source

#### pub fn propagate_version(self, yes: bool) -> Command

Specifies to use the version of the current command for all `subcommands`.

Defaults to `false`; subcommands have independent version strings from their parents.

NOTE: This choice is propagated to all child subcommands.

##### §Examples

    Command::new("myprog")
        .version("v1.1")
        .propagate_version(true)
        .subcommand(Command::new("test"))
        .get_matches();
    // running `$ myprog test --version` will display
    // "myprog-test v1.1"

Source

#### pub fn next_line_help(self, yes: bool) -> Command

Places the help string for all arguments and subcommands on the line after them.

NOTE: This choice is propagated to all child subcommands.

##### §Examples

    Command::new("myprog")
        .next_line_help(true)
        .get_matches();

Source

#### pub fn disable_help_flag(self, yes: bool) -> Command

Disables `-h` and `--help` flag.

NOTE: This choice is propagated to all child subcommands.

##### §Examples

    let res = Command::new("myprog")
        .disable_help_flag(true)
        .try_get_matches_from(vec![
            "myprog", "-h"
        ]);
    assert!(res.is_err());
    assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);

You can create a custom help flag with `ArgAction::Help`, `ArgAction::HelpShort`, or `ArgAction::HelpLong`

    let mut cmd = Command::new("myprog")
        // Change help short flag to `?`
        .disable_help_flag(true)
        .arg(
            Arg::new("help")
                .short('?')
                .long("help")
                .action(ArgAction::Help)
                .help("Print help")
        );

    let res = cmd.try_get_matches_from_mut(vec![
            "myprog", "-h"
        ]);
    assert!(res.is_err());
    assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);

    let res = cmd.try_get_matches_from_mut(vec![
            "myprog", "-?"
        ]);
    assert!(res.is_err());
    assert_eq!(res.unwrap_err().kind(), ErrorKind::DisplayHelp);

Source

#### pub fn disable_help_subcommand(self, yes: bool) -> Command

Disables the `help` `subcommand`.

NOTE: This choice is propagated to all child subcommands.

##### §Examples

    let res = Command::new("myprog")
        .disable_help_subcommand(true)
        // Normally, creating a subcommand causes a `help` subcommand to automatically
        // be generated as well
        .subcommand(Command::new("test"))
        .try_get_matches_from(vec![
            "myprog", "help"
        ]);
    assert!(res.is_err());
    assert_eq!(res.unwrap_err().kind(), ErrorKind::InvalidSubcommand);

Source

#### pub fn disable_colored_help(self, yes: bool) -> Command

Disables colorized help messages.

NOTE: This choice is propagated to all child subcommands.

##### §Examples

    Command::new("myprog")
        .disable_colored_help(true)
        .get_matches();

Source

#### pub fn help_expected(self, yes: bool) -> Command

Panic if help descriptions are omitted.

NOTE: When deriving `Parser`, you could instead check this at compile-time with `#![deny(missing_docs)]`

NOTE: This choice is propagated to all child subcommands.

##### §Examples

    Command::new("myprog")
        .help_expected(true)
        .arg(
            Arg::new("foo").help("It does foo stuff")
            // As required via `help_expected`, a help message was supplied
         )

##### §Panics

On debug builds:

    Command::new("myapp")
        .help_expected(true)
        .arg(
            Arg::new("foo")
            // Someone forgot to put .about("...") here
            // Since the setting `help_expected` is activated, this will lead to
            // a panic (if you are in debug mode)
        )

Source

#### pub fn hide_possible_values(self, yes: bool) -> Command

Tells `clap` not to print possible values when displaying help information.

This can be useful if there are many values, or they are explained elsewhere.

To set this per argument, see `Arg::hide_possible_values`.

NOTE: This choice is propagated to all child subcommands.

Source

#### pub fn infer_long_args(self, yes: bool) -> Command

Allow partial matches of long arguments or their aliases.

For example, to match an argument named `--test`, one could use `--t`, `--te`, `--tes`, and `--test`.

NOTE: The match must not be ambiguous at all in order to succeed. i.e. to match `--te` to `--test` there could not also be another argument or alias `--temp` because both start with `--te`

NOTE: This choice is propagated to all child subcommands.

Source

#### pub fn infer_subcommands(self, yes: bool) -> Command

Allow partial matches of subcommand names and their aliases.

For example, to match a subcommand named `test`, one could use `t`, `te`, `tes`, and `test`.

NOTE: The match must not be ambiguous at all in order to succeed. i.e. to match `te` to `test` there could not also be a subcommand or alias `temp` because both start with `te`

WARNING: This setting can interfere with positional/free arguments, take care when designing CLIs which allow inferred subcommands and have potential positional/free arguments whose values could start with the same characters as subcommands. If this is the case, it’s recommended to use settings such as `Command::args_conflicts_with_subcommands` in conjunction with this setting.

NOTE: This choice is propagated to all child subcommands.

##### §Examples

    let m = Command::new("prog")
        .infer_subcommands(true)
        .subcommand(Command::new("test"))
        .get_matches_from(vec![
            "prog", "te"
        ]);
    assert_eq!(m.subcommand_name(), Some("test"));

Source§

### impl Command

#### §Command-specific Settings

These apply only to the current command and are not inherited by subcommands.

Source

#### pub fn name(self, name: impl Into<Str>) -> Command

(Re)Sets the program’s name.

See `Command::new` for more details.

##### §Examples

ⓘ

    let cmd = clap::command!()
        .name("foo");

    // continued logic goes here, such as `cmd.get_matches()` etc.

Source

#### pub fn bin_name(self, name: impl IntoResettable<String>) -> Command

Overrides the runtime-determined name of the binary for help and error messages.

This should only be used when absolutely necessary, such as when the binary name for your application is misleading, or perhaps not how the user should invoke your program.

TIP: When building things such as third party `cargo` subcommands, this setting should be used!

NOTE: This does not change or set the name of the binary file on disk. It only changes what clap thinks the name is for the purposes of error or help messages.

##### §Examples

    Command::new("My Program")
         .bin_name("my_binary")

Source

#### pub fn display_name(self, name: impl IntoResettable<String>) -> Command

Overrides the runtime-determined display name of the program for help and error messages.

##### §Examples

    Command::new("My Program")
         .display_name("my_program")

Source

#### pub fn author(self, author: impl IntoResettable<Str>) -> Command

Sets the author(s) for the help message.

TIP: Use `clap`s convenience macro `crate_authors!` to automatically set your application’s author(s) to the same thing as your crate at compile time.

NOTE: A custom `help_template` is needed for author to show up.

##### §Examples

    Command::new("myprog")
         .author("Me, me@mymain.com")

Source

#### pub fn about(self, about: impl IntoResettable<StyledStr>) -> Command

Sets the program’s description for the short help (`-h`).

If `Command::long_about` is not specified, this message will be displayed for `--help`.

See also `crate_description!`.

##### §Examples

    Command::new("myprog")
        .about("Does really amazing things for great people")

##### Examples found in repository?

examples/multicall-busybox.rs (line 8)

    6fn applet_commands() -> [Command; 2] {
    7    [
    8        Command::new("true").about("does nothing successfully"),
    9        Command::new("false").about("does nothing unsuccessfully"),
    10    ]
    11}

More examples
Hide additional examples
examples/tutorial_builder/02_apps.rs (line 6)

    3fn main() {
    4    let matches = Command::new("MyApp")
    5        .version("1.0")
    6        .about("Does awesome things")
    7        .arg(arg!(--two <VALUE>).required(true))
    8        .arg(arg!(--one <VALUE>).required(true))
    9        .get_matches();
    10
    11    println!(
    12        "two: {:?}",
    13        matches.get_one::<String>("two").expect("required")
    14    );
    15    println!(
    16        "one: {:?}",
    17        matches.get_one::<String>("one").expect("required")
    18    );
    19}

examples/multicall-hostname.rs (line 9)

    3fn main() {
    4    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    5        .multicall(true)
    6        .arg_required_else_help(true)
    7        .subcommand_value_name("APPLET")
    8        .subcommand_help_heading("APPLETS")
    9        .subcommand(Command::new("hostname").about("show hostname part of FQDN"))
    10        .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN"));
    11
    12    match cmd.get_matches().subcommand_name() {
    13        Some("hostname") => println!("www"),
    14        Some("dnsdomainname") => println!("example.com"),
    15        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    16    }
    17}

examples/repl.rs (line 73)

    51fn cli() -> Command {
    52    // strip out usage
    53    const PARSER_TEMPLATE: &str = "\
    54        {all-args}
    55    ";
    56    // strip out name/version
    57    const APPLET_TEMPLATE: &str = "\
    58        {about-with-newline}\n\
    59        {usage-heading}\n    {usage}\n\
    60        \n\
    61        {all-args}{after-help}\
    62    ";
    63
    64    Command::new("repl")
    65        .multicall(true)
    66        .arg_required_else_help(true)
    67        .subcommand_required(true)
    68        .subcommand_value_name("APPLET")
    69        .subcommand_help_heading("APPLETS")
    70        .help_template(PARSER_TEMPLATE)
    71        .subcommand(
    72            Command::new("ping")
    73                .about("Get a response")
    74                .help_template(APPLET_TEMPLATE),
    75        )
    76        .subcommand(
    77            Command::new("quit")
    78                .alias("exit")
    79                .about("Quit the REPL")
    80                .help_template(APPLET_TEMPLATE),
    81        )
    82}

examples/git.rs (line 8)

    6fn cli() -> Command {
    7    Command::new("git")
    8        .about("A fictional versioning CLI")
    9        .subcommand_required(true)
    10        .arg_required_else_help(true)
    11        .allow_external_subcommands(true)
    12        .subcommand(
    13            Command::new("clone")
    14                .about("Clones repos")
    15                .arg(arg!(<REMOTE> "The remote to clone"))
    16                .arg_required_else_help(true),
    17        )
    18        .subcommand(
    19            Command::new("diff")
    20                .about("Compare two commits")
    21                .arg(arg!(base: [COMMIT]))
    22                .arg(arg!(head: [COMMIT]))
    23                .arg(arg!(path: [PATH]).last(true))
    24                .arg(
    25                    arg!(--color <WHEN>)
    26                        .value_parser(["always", "auto", "never"])
    27                        .num_args(0..=1)
    28                        .require_equals(true)
    29                        .default_value("auto")
    30                        .default_missing_value("always"),
    31                ),
    32        )
    33        .subcommand(
    34            Command::new("push")
    35                .about("pushes things")
    36                .arg(arg!(<REMOTE> "The remote to target"))
    37                .arg_required_else_help(true),
    38        )
    39        .subcommand(
    40            Command::new("add")
    41                .about("adds things")
    42                .arg_required_else_help(true)
    43                .arg(arg!(<PATH> ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))),
    44        )
    45        .subcommand(
    46            Command::new("stash")
    47                .args_conflicts_with_subcommands(true)
    48                .flatten_help(true)
    49                .args(push_args())
    50                .subcommand(Command::new("push").args(push_args()))
    51                .subcommand(Command::new("pop").arg(arg!([STASH])))
    52                .subcommand(Command::new("apply").arg(arg!([STASH]))),
    53        )
    54}

examples/pacman.rs (line 5)

    3fn cli() -> Command {
    4    Command::new("pacman")
    5        .about("package manager utility")
    6        .version("5.2.1")
    7        .subcommand_required(true)
    8        .arg_required_else_help(true)
    9        // Query subcommand
    10        //
    11        // Only a few of its arguments are implemented below.
    12        .subcommand(
    13            Command::new("query")
    14                .short_flag('Q')
    15                .long_flag("query")
    16                .about("Query the package database.")
    17                .arg(
    18                    Arg::new("search")
    19                        .short('s')
    20                        .long("search")
    21                        .help("search locally installed packages for matching strings")
    22                        .conflicts_with("info")
    23                        .action(ArgAction::Set)
    24                        .num_args(1..),
    25                )
    26                .arg(
    27                    Arg::new("info")
    28                        .long("info")
    29                        .short('i')
    30                        .conflicts_with("search")
    31                        .help("view package information")
    32                        .action(ArgAction::Set)
    33                        .num_args(1..),
    34                ),
    35        )
    36        // Sync subcommand
    37        //
    38        // Only a few of its arguments are implemented below.
    39        .subcommand(
    40            Command::new("sync")
    41                .short_flag('S')
    42                .long_flag("sync")
    43                .about("Synchronize packages.")
    44                .arg(
    45                    Arg::new("search")
    46                        .short('s')
    47                        .long("search")
    48                        .conflicts_with("info")
    49                        .action(ArgAction::Set)
    50                        .num_args(1..)
    51                        .help("search remote repositories for matching strings"),
    52                )
    53                .arg(
    54                    Arg::new("info")
    55                        .long("info")
    56                        .conflicts_with("search")
    57                        .short('i')
    58                        .action(ArgAction::SetTrue)
    59                        .help("view package information"),
    60                )
    61                .arg(
    62                    Arg::new("package")
    63                        .help("packages")
    64                        .required_unless_present("search")
    65                        .action(ArgAction::Set)
    66                        .num_args(1..),
    67                ),
    68        )
    69}

Source

#### pub fn long_about(self, long_about: impl IntoResettable<StyledStr>) -> Command

Sets the program’s description for the long help (`--help`).

If not set, `Command::about` will be used for long help in addition to short help (`-h`).

NOTE: Only `Command::about` (short format) is used in completion script generation in order to be concise.

##### §Examples

    Command::new("myprog")
        .long_about(
    "Does really amazing things to great people. Now let's talk a little
     more in depth about how this subcommand really works. It may take about
     a few lines of text, but that's ok!")

Source

#### pub fn after_help(self, help: impl IntoResettable<StyledStr>) -> Command

Free-form help text for after auto-generated short help (`-h`).

This is often used to describe how to use the arguments, caveats to be noted, or license and contact information.

If `Command::after_long_help` is not specified, this message will be displayed for `--help`.

##### §Examples

    Command::new("myprog")
        .after_help("Does really amazing things for great people... but be careful with -R!")

Source

#### pub fn after_long_help(self, help: impl IntoResettable<StyledStr>) -> Command

Free-form help text for after auto-generated long help (`--help`).

This is often used to describe how to use the arguments, caveats to be noted, or license and contact information.

If not set, `Command::after_help` will be used for long help in addition to short help (`-h`).

##### §Examples

    Command::new("myprog")
        .after_long_help("Does really amazing things to great people... but be careful with -R, \
                         like, for real, be careful with this!")

Source

#### pub fn before_help(self, help: impl IntoResettable<StyledStr>) -> Command

Free-form help text for before auto-generated short help (`-h`).

This is often used for header, copyright, or license information.

If `Command::before_long_help` is not specified, this message will be displayed for `--help`.

##### §Examples

    Command::new("myprog")
        .before_help("Some info I'd like to appear before the help info")

Source

#### pub fn before_long_help(self, help: impl IntoResettable<StyledStr>) -> Command

Free-form help text for before auto-generated long help (`--help`).

This is often used for header, copyright, or license information.

If not set, `Command::before_help` will be used for long help in addition to short help (`-h`).

##### §Examples

    Command::new("myprog")
        .before_long_help("Some verbose and long info I'd like to appear before the help info")

Source

#### pub fn version(self, ver: impl IntoResettable<Str>) -> Command

Sets the version for the short version (`-V`) and help messages.

If `Command::long_version` is not specified, this message will be displayed for `--version`.

TIP: Use `clap`s convenience macro `crate_version!` to automatically set your application’s version to the same thing as your crate at compile time.

##### §Examples

    Command::new("myprog")
        .version("v0.1.24")

##### Examples found in repository?

examples/tutorial_builder/02_apps.rs (line 5)

    3fn main() {
    4    let matches = Command::new("MyApp")
    5        .version("1.0")
    6        .about("Does awesome things")
    7        .arg(arg!(--two <VALUE>).required(true))
    8        .arg(arg!(--one <VALUE>).required(true))
    9        .get_matches();
    10
    11    println!(
    12        "two: {:?}",
    13        matches.get_one::<String>("two").expect("required")
    14    );
    15    println!(
    16        "one: {:?}",
    17        matches.get_one::<String>("one").expect("required")
    18    );
    19}

More examples
Hide additional examples
examples/pacman.rs (line 6)

    3fn cli() -> Command {
    4    Command::new("pacman")
    5        .about("package manager utility")
    6        .version("5.2.1")
    7        .subcommand_required(true)
    8        .arg_required_else_help(true)
    9        // Query subcommand
    10        //
    11        // Only a few of its arguments are implemented below.
    12        .subcommand(
    13            Command::new("query")
    14                .short_flag('Q')
    15                .long_flag("query")
    16                .about("Query the package database.")
    17                .arg(
    18                    Arg::new("search")
    19                        .short('s')
    20                        .long("search")
    21                        .help("search locally installed packages for matching strings")
    22                        .conflicts_with("info")
    23                        .action(ArgAction::Set)
    24                        .num_args(1..),
    25                )
    26                .arg(
    27                    Arg::new("info")
    28                        .long("info")
    29                        .short('i')
    30                        .conflicts_with("search")
    31                        .help("view package information")
    32                        .action(ArgAction::Set)
    33                        .num_args(1..),
    34                ),
    35        )
    36        // Sync subcommand
    37        //
    38        // Only a few of its arguments are implemented below.
    39        .subcommand(
    40            Command::new("sync")
    41                .short_flag('S')
    42                .long_flag("sync")
    43                .about("Synchronize packages.")
    44                .arg(
    45                    Arg::new("search")
    46                        .short('s')
    47                        .long("search")
    48                        .conflicts_with("info")
    49                        .action(ArgAction::Set)
    50                        .num_args(1..)
    51                        .help("search remote repositories for matching strings"),
    52                )
    53                .arg(
    54                    Arg::new("info")
    55                        .long("info")
    56                        .conflicts_with("search")
    57                        .short('i')
    58                        .action(ArgAction::SetTrue)
    59                        .help("view package information"),
    60                )
    61                .arg(
    62                    Arg::new("package")
    63                        .help("packages")
    64                        .required_unless_present("search")
    65                        .action(ArgAction::Set)
    66                        .num_args(1..),
    67                ),
    68        )
    69}

Source

#### pub fn long_version(self, ver: impl IntoResettable<Str>) -> Command

Sets the version for the long version (`--version`) and help messages.

If `Command::version` is not specified, this message will be displayed for `-V`.

TIP: Use `clap`s convenience macro `crate_version!` to automatically set your application’s version to the same thing as your crate at compile time.

##### §Examples

    Command::new("myprog")
        .long_version(
    "v0.1.24
     commit: abcdef89726d
     revision: 123
     release: 2
     binary: myprog")

Source

#### pub fn override_usage(self, usage: impl IntoResettable<StyledStr>) -> Command

Overrides the `clap` generated usage string for help and error messages.

NOTE: Using this setting disables `clap`s “context-aware” usage strings. After this setting is set, this will be the only usage string displayed to the user!

NOTE: Multiple usage lines may be present in the usage argument, but some rules need to be followed to ensure the usage lines are formatted correctly by the default help formatter:

- Do not indent the first usage line.
- Indent all subsequent usage lines with seven spaces.
- The last line must not end with a newline.

##### §Examples

    Command::new("myprog")
        .override_usage("myapp [-clDas] <some_file>")

Or for multiple usage lines:

    Command::new("myprog")
        .override_usage(
            "myapp -X [-a] [-b] <file>\n       \
             myapp -Y [-c] <file1> <file2>\n       \
             myapp -Z [-d|-e]"
        )

Source

#### pub fn override_help(self, help: impl IntoResettable<StyledStr>) -> Command

Overrides the `clap` generated help message (both `-h` and `--help`).

This should only be used when the auto-generated message does not suffice.

NOTE: This only replaces the help message for the current command, meaning if you are using subcommands, those help messages will still be auto-generated unless you specify a `Command::override_help` for them as well.

##### §Examples

    Command::new("myapp")
        .override_help("myapp v1.0\n\
               Does awesome things\n\
               (C) me@mail.com\n\n\

               Usage: myapp <opts> <command>\n\n\

               Options:\n\
               -h, --help       Display this message\n\
               -V, --version    Display version info\n\
               -s <stuff>       Do something with stuff\n\
               -v               Be verbose\n\n\

               Commands:\n\
               help             Print this message\n\
               work             Do some work")

Source

#### pub fn help_template(self, s: impl IntoResettable<StyledStr>) -> Command

Available on crate feature `help` only.

Sets the help template to be used, overriding the default format.

Tags are given inside curly brackets.

Valid tags are:

- `{name}` - Display name for the (sub-)command.
- `{bin}` - Binary name.(deprecated)
- `{version}` - Version number.
- `{author}` - Author information.
- `{author-with-newline}` - Author followed by `\n`.
- `{author-section}` - Author preceded and followed by `\n`.
- `{about}` - General description (from `Command::about` or `Command::long_about`).
- `{about-with-newline}` - About followed by `\n`.
- `{about-section}` - About preceded and followed by ‘\n’.
- `{usage-heading}` - Automatically generated usage heading.
- `{usage}` - Automatically generated or given usage string.
- `{all-args}` - Help for all arguments (options, flags, positional arguments, and subcommands) including titles.
- `{options}` - Help for options.
- `{positionals}` - Help for positional arguments.
- `{subcommands}` - Help for subcommands.
- `{tab}` - Standard tab sized used within clap
- `{after-help}` - Help from `Command::after_help` or `Command::after_long_help`.
- `{before-help}` - Help from `Command::before_help` or `Command::before_long_help`.

##### §Examples

For a very brief help:

    Command::new("myprog")
        .version("1.0")
        .help_template("{name} ({version}) - {usage}")

For showing more application context:

    Command::new("myprog")
        .version("1.0")
        .help_template("\
    {before-help}{name} {version}
    {author-with-newline}{about-with-newline}
    {usage-heading} {usage}

    {all-args}{after-help}
    ")

##### Examples found in repository?

examples/repl.rs (line 70)

    51fn cli() -> Command {
    52    // strip out usage
    53    const PARSER_TEMPLATE: &str = "\
    54        {all-args}
    55    ";
    56    // strip out name/version
    57    const APPLET_TEMPLATE: &str = "\
    58        {about-with-newline}\n\
    59        {usage-heading}\n    {usage}\n\
    60        \n\
    61        {all-args}{after-help}\
    62    ";
    63
    64    Command::new("repl")
    65        .multicall(true)
    66        .arg_required_else_help(true)
    67        .subcommand_required(true)
    68        .subcommand_value_name("APPLET")
    69        .subcommand_help_heading("APPLETS")
    70        .help_template(PARSER_TEMPLATE)
    71        .subcommand(
    72            Command::new("ping")
    73                .about("Get a response")
    74                .help_template(APPLET_TEMPLATE),
    75        )
    76        .subcommand(
    77            Command::new("quit")
    78                .alias("exit")
    79                .about("Quit the REPL")
    80                .help_template(APPLET_TEMPLATE),
    81        )
    82}

Source

#### pub fn flatten_help(self, yes: bool) -> Command

Flatten subcommand help into the current command’s help

This shows a summary of subcommands within the usage and help for the current command, similar to `git stash --help` showing information on `push`, `pop`, etc. To see more information, a user can still pass `--help` to the individual subcommands.

##### Examples found in repository?

examples/git.rs (line 48)

    6fn cli() -> Command {
    7    Command::new("git")
    8        .about("A fictional versioning CLI")
    9        .subcommand_required(true)
    10        .arg_required_else_help(true)
    11        .allow_external_subcommands(true)
    12        .subcommand(
    13            Command::new("clone")
    14                .about("Clones repos")
    15                .arg(arg!(<REMOTE> "The remote to clone"))
    16                .arg_required_else_help(true),
    17        )
    18        .subcommand(
    19            Command::new("diff")
    20                .about("Compare two commits")
    21                .arg(arg!(base: [COMMIT]))
    22                .arg(arg!(head: [COMMIT]))
    23                .arg(arg!(path: [PATH]).last(true))
    24                .arg(
    25                    arg!(--color <WHEN>)
    26                        .value_parser(["always", "auto", "never"])
    27                        .num_args(0..=1)
    28                        .require_equals(true)
    29                        .default_value("auto")
    30                        .default_missing_value("always"),
    31                ),
    32        )
    33        .subcommand(
    34            Command::new("push")
    35                .about("pushes things")
    36                .arg(arg!(<REMOTE> "The remote to target"))
    37                .arg_required_else_help(true),
    38        )
    39        .subcommand(
    40            Command::new("add")
    41                .about("adds things")
    42                .arg_required_else_help(true)
    43                .arg(arg!(<PATH> ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))),
    44        )
    45        .subcommand(
    46            Command::new("stash")
    47                .args_conflicts_with_subcommands(true)
    48                .flatten_help(true)
    49                .args(push_args())
    50                .subcommand(Command::new("push").args(push_args()))
    51                .subcommand(Command::new("pop").arg(arg!([STASH])))
    52                .subcommand(Command::new("apply").arg(arg!([STASH]))),
    53        )
    54}

Source

#### pub fn next_help_heading(self, heading: impl IntoResettable<Str>) -> Command

Set the default section heading for future args.

This will be used for any arg that hasn’t had `Arg::help_heading` called.

This is useful if the default `Options` or `Arguments` headings are not specific enough for one’s use case.

For subcommands, see `Command::subcommand_help_heading`

Source

#### pub fn next_display_order(self, disp_ord: impl IntoResettable<usize>) -> Command

Change the starting value for assigning future display orders for args.

This will be used for any arg that hasn’t had `Arg::display_order` called.

Source

#### pub fn arg_required_else_help(self, yes: bool) -> Command

Exit gracefully if no arguments are present (e.g. `$ myprog`).

NOTE: `subcommands` count as arguments

##### §Examples

    Command::new("myprog")
        .arg_required_else_help(true);

##### Examples found in repository?

examples/multicall-hostname.rs (line 6)

    3fn main() {
    4    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    5        .multicall(true)
    6        .arg_required_else_help(true)
    7        .subcommand_value_name("APPLET")
    8        .subcommand_help_heading("APPLETS")
    9        .subcommand(Command::new("hostname").about("show hostname part of FQDN"))
    10        .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN"));
    11
    12    match cmd.get_matches().subcommand_name() {
    13        Some("hostname") => println!("www"),
    14        Some("dnsdomainname") => println!("example.com"),
    15        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    16    }
    17}

More examples
Hide additional examples
examples/repl.rs (line 66)

    51fn cli() -> Command {
    52    // strip out usage
    53    const PARSER_TEMPLATE: &str = "\
    54        {all-args}
    55    ";
    56    // strip out name/version
    57    const APPLET_TEMPLATE: &str = "\
    58        {about-with-newline}\n\
    59        {usage-heading}\n    {usage}\n\
    60        \n\
    61        {all-args}{after-help}\
    62    ";
    63
    64    Command::new("repl")
    65        .multicall(true)
    66        .arg_required_else_help(true)
    67        .subcommand_required(true)
    68        .subcommand_value_name("APPLET")
    69        .subcommand_help_heading("APPLETS")
    70        .help_template(PARSER_TEMPLATE)
    71        .subcommand(
    72            Command::new("ping")
    73                .about("Get a response")
    74                .help_template(APPLET_TEMPLATE),
    75        )
    76        .subcommand(
    77            Command::new("quit")
    78                .alias("exit")
    79                .about("Quit the REPL")
    80                .help_template(APPLET_TEMPLATE),
    81        )
    82}

examples/multicall-busybox.rs (line 18)

    13fn main() {
    14    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    15        .multicall(true)
    16        .subcommand(
    17            Command::new("busybox")
    18                .arg_required_else_help(true)
    19                .subcommand_value_name("APPLET")
    20                .subcommand_help_heading("APPLETS")
    21                .arg(
    22                    Arg::new("install")
    23                        .long("install")
    24                        .help("Install hardlinks for all subcommands in path")
    25                        .exclusive(true)
    26                        .action(ArgAction::Set)
    27                        .default_missing_value("/usr/local/bin")
    28                        .value_parser(value_parser!(PathBuf)),
    29                )
    30                .subcommands(applet_commands()),
    31        )
    32        .subcommands(applet_commands());
    33
    34    let matches = cmd.get_matches();
    35    let mut subcommand = matches.subcommand();
    36    if let Some(("busybox", cmd)) = subcommand {
    37        if cmd.contains_id("install") {
    38            unimplemented!("Make hardlinks to the executable here");
    39        }
    40        subcommand = cmd.subcommand();
    41    }
    42    match subcommand {
    43        Some(("false", _)) => exit(1),
    44        Some(("true", _)) => exit(0),
    45        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    46    }
    47}

examples/git.rs (line 10)

    6fn cli() -> Command {
    7    Command::new("git")
    8        .about("A fictional versioning CLI")
    9        .subcommand_required(true)
    10        .arg_required_else_help(true)
    11        .allow_external_subcommands(true)
    12        .subcommand(
    13            Command::new("clone")
    14                .about("Clones repos")
    15                .arg(arg!(<REMOTE> "The remote to clone"))
    16                .arg_required_else_help(true),
    17        )
    18        .subcommand(
    19            Command::new("diff")
    20                .about("Compare two commits")
    21                .arg(arg!(base: [COMMIT]))
    22                .arg(arg!(head: [COMMIT]))
    23                .arg(arg!(path: [PATH]).last(true))
    24                .arg(
    25                    arg!(--color <WHEN>)
    26                        .value_parser(["always", "auto", "never"])
    27                        .num_args(0..=1)
    28                        .require_equals(true)
    29                        .default_value("auto")
    30                        .default_missing_value("always"),
    31                ),
    32        )
    33        .subcommand(
    34            Command::new("push")
    35                .about("pushes things")
    36                .arg(arg!(<REMOTE> "The remote to target"))
    37                .arg_required_else_help(true),
    38        )
    39        .subcommand(
    40            Command::new("add")
    41                .about("adds things")
    42                .arg_required_else_help(true)
    43                .arg(arg!(<PATH> ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))),
    44        )
    45        .subcommand(
    46            Command::new("stash")
    47                .args_conflicts_with_subcommands(true)
    48                .flatten_help(true)
    49                .args(push_args())
    50                .subcommand(Command::new("push").args(push_args()))
    51                .subcommand(Command::new("pop").arg(arg!([STASH])))
    52                .subcommand(Command::new("apply").arg(arg!([STASH]))),
    53        )
    54}

examples/pacman.rs (line 8)

    3fn cli() -> Command {
    4    Command::new("pacman")
    5        .about("package manager utility")
    6        .version("5.2.1")
    7        .subcommand_required(true)
    8        .arg_required_else_help(true)
    9        // Query subcommand
    10        //
    11        // Only a few of its arguments are implemented below.
    12        .subcommand(
    13            Command::new("query")
    14                .short_flag('Q')
    15                .long_flag("query")
    16                .about("Query the package database.")
    17                .arg(
    18                    Arg::new("search")
    19                        .short('s')
    20                        .long("search")
    21                        .help("search locally installed packages for matching strings")
    22                        .conflicts_with("info")
    23                        .action(ArgAction::Set)
    24                        .num_args(1..),
    25                )
    26                .arg(
    27                    Arg::new("info")
    28                        .long("info")
    29                        .short('i')
    30                        .conflicts_with("search")
    31                        .help("view package information")
    32                        .action(ArgAction::Set)
    33                        .num_args(1..),
    34                ),
    35        )
    36        // Sync subcommand
    37        //
    38        // Only a few of its arguments are implemented below.
    39        .subcommand(
    40            Command::new("sync")
    41                .short_flag('S')
    42                .long_flag("sync")
    43                .about("Synchronize packages.")
    44                .arg(
    45                    Arg::new("search")
    46                        .short('s')
    47                        .long("search")
    48                        .conflicts_with("info")
    49                        .action(ArgAction::Set)
    50                        .num_args(1..)
    51                        .help("search remote repositories for matching strings"),
    52                )
    53                .arg(
    54                    Arg::new("info")
    55                        .long("info")
    56                        .conflicts_with("search")
    57                        .short('i')
    58                        .action(ArgAction::SetTrue)
    59                        .help("view package information"),
    60                )
    61                .arg(
    62                    Arg::new("package")
    63                        .help("packages")
    64                        .required_unless_present("search")
    65                        .action(ArgAction::Set)
    66                        .num_args(1..),
    67                ),
    68        )
    69}

Source

#### pub fn allow_missing_positional(self, yes: bool) -> Command

Allows one to implement two styles of CLIs where positionals can be used out of order.

The first example is a CLI where the second to last positional argument is optional, but the final positional argument is required. Such as `$ prog [optional] <required>` where one of the two following usages is allowed:

- `$ prog [optional] <required>`
- `$ prog <required>`

This would otherwise not be allowed. This is useful when `[optional]` has a default value.

Note: when using this style of “missing positionals” the final positional must be required if `--` will not be used to skip to the final positional argument.

Note: This style also only allows a single positional argument to be “skipped” without the use of `--`. To skip more than one, see the second example.

The second example is when one wants to skip multiple optional positional arguments, and use of the `--` operator is OK (but not required if all arguments will be specified anyways).

For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where `baz` accepts multiple values (similar to man `ARGS...` style training arguments).

With this setting the following invocations are possible:

- `$ prog foo bar baz1 baz2 baz3`
- `$ prog foo -- baz1 baz2 baz3`
- `$ prog -- baz1 baz2 baz3`

##### §Examples

Style number one from above:

    // Assume there is an external subcommand named "subcmd"
    let m = Command::new("myprog")
        .allow_missing_positional(true)
        .arg(Arg::new("arg1"))
        .arg(Arg::new("arg2")
            .required(true))
        .get_matches_from(vec![
            "prog", "other"
        ]);

    assert_eq!(m.get_one::<String>("arg1"), None);
    assert_eq!(m.get_one::<String>("arg2").unwrap(), "other");

Now the same example, but using a default value for the first optional positional argument

    // Assume there is an external subcommand named "subcmd"
    let m = Command::new("myprog")
        .allow_missing_positional(true)
        .arg(Arg::new("arg1")
            .default_value("something"))
        .arg(Arg::new("arg2")
            .required(true))
        .get_matches_from(vec![
            "prog", "other"
        ]);

    assert_eq!(m.get_one::<String>("arg1").unwrap(), "something");
    assert_eq!(m.get_one::<String>("arg2").unwrap(), "other");

Style number two from above:

    // Assume there is an external subcommand named "subcmd"
    let m = Command::new("myprog")
        .allow_missing_positional(true)
        .arg(Arg::new("foo"))
        .arg(Arg::new("bar"))
        .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..))
        .get_matches_from(vec![
            "prog", "foo", "bar", "baz1", "baz2", "baz3"
        ]);

    assert_eq!(m.get_one::<String>("foo").unwrap(), "foo");
    assert_eq!(m.get_one::<String>("bar").unwrap(), "bar");
    assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);

Now nofice if we don’t specify `foo` or `baz` but use the `--` operator.

    // Assume there is an external subcommand named "subcmd"
    let m = Command::new("myprog")
        .allow_missing_positional(true)
        .arg(Arg::new("foo"))
        .arg(Arg::new("bar"))
        .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..))
        .get_matches_from(vec![
            "prog", "--", "baz1", "baz2", "baz3"
        ]);

    assert_eq!(m.get_one::<String>("foo"), None);
    assert_eq!(m.get_one::<String>("bar"), None);
    assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);

Source§

### impl Command

#### §Subcommand-specific Settings

Source

#### pub fn short_flag(self, short: impl IntoResettable<char>) -> Command

Sets the short version of the subcommand flag without the preceding `-`.

Allows the subcommand to be used as if it were an `Arg::short`.

##### §Examples

    let matches = Command::new("pacman")
        .subcommand(
            Command::new("sync").short_flag('S').arg(
                Arg::new("search")
                    .short('s')
                    .long("search")
                    .action(ArgAction::SetTrue)
                    .help("search remote repositories for matching strings"),
            ),
        )
        .get_matches_from(vec!["pacman", "-Ss"]);

    assert_eq!(matches.subcommand_name().unwrap(), "sync");
    let sync_matches = matches.subcommand_matches("sync").unwrap();
    assert!(sync_matches.get_flag("search"));

##### Examples found in repository?

examples/pacman.rs (line 14)

    3fn cli() -> Command {
    4    Command::new("pacman")
    5        .about("package manager utility")
    6        .version("5.2.1")
    7        .subcommand_required(true)
    8        .arg_required_else_help(true)
    9        // Query subcommand
    10        //
    11        // Only a few of its arguments are implemented below.
    12        .subcommand(
    13            Command::new("query")
    14                .short_flag('Q')
    15                .long_flag("query")
    16                .about("Query the package database.")
    17                .arg(
    18                    Arg::new("search")
    19                        .short('s')
    20                        .long("search")
    21                        .help("search locally installed packages for matching strings")
    22                        .conflicts_with("info")
    23                        .action(ArgAction::Set)
    24                        .num_args(1..),
    25                )
    26                .arg(
    27                    Arg::new("info")
    28                        .long("info")
    29                        .short('i')
    30                        .conflicts_with("search")
    31                        .help("view package information")
    32                        .action(ArgAction::Set)
    33                        .num_args(1..),
    34                ),
    35        )
    36        // Sync subcommand
    37        //
    38        // Only a few of its arguments are implemented below.
    39        .subcommand(
    40            Command::new("sync")
    41                .short_flag('S')
    42                .long_flag("sync")
    43                .about("Synchronize packages.")
    44                .arg(
    45                    Arg::new("search")
    46                        .short('s')
    47                        .long("search")
    48                        .conflicts_with("info")
    49                        .action(ArgAction::Set)
    50                        .num_args(1..)
    51                        .help("search remote repositories for matching strings"),
    52                )
    53                .arg(
    54                    Arg::new("info")
    55                        .long("info")
    56                        .conflicts_with("search")
    57                        .short('i')
    58                        .action(ArgAction::SetTrue)
    59                        .help("view package information"),
    60                )
    61                .arg(
    62                    Arg::new("package")
    63                        .help("packages")
    64                        .required_unless_present("search")
    65                        .action(ArgAction::Set)
    66                        .num_args(1..),
    67                ),
    68        )
    69}

Source

#### pub fn long_flag(self, long: impl Into<Str>) -> Command

Sets the long version of the subcommand flag without the preceding `--`.

Allows the subcommand to be used as if it were an `Arg::long`.

NOTE: Any leading `-` characters will be stripped.

##### §Examples

To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however, will not be stripped (i.e. `sync-file` is allowed).

    let matches = Command::new("pacman")
        .subcommand(
            Command::new("sync").long_flag("sync").arg(
                Arg::new("search")
                    .short('s')
                    .long("search")
                    .action(ArgAction::SetTrue)
                    .help("search remote repositories for matching strings"),
            ),
        )
        .get_matches_from(vec!["pacman", "--sync", "--search"]);

    assert_eq!(matches.subcommand_name().unwrap(), "sync");
    let sync_matches = matches.subcommand_matches("sync").unwrap();
    assert!(sync_matches.get_flag("search"));

##### Examples found in repository?

examples/pacman.rs (line 15)

    3fn cli() -> Command {
    4    Command::new("pacman")
    5        .about("package manager utility")
    6        .version("5.2.1")
    7        .subcommand_required(true)
    8        .arg_required_else_help(true)
    9        // Query subcommand
    10        //
    11        // Only a few of its arguments are implemented below.
    12        .subcommand(
    13            Command::new("query")
    14                .short_flag('Q')
    15                .long_flag("query")
    16                .about("Query the package database.")
    17                .arg(
    18                    Arg::new("search")
    19                        .short('s')
    20                        .long("search")
    21                        .help("search locally installed packages for matching strings")
    22                        .conflicts_with("info")
    23                        .action(ArgAction::Set)
    24                        .num_args(1..),
    25                )
    26                .arg(
    27                    Arg::new("info")
    28                        .long("info")
    29                        .short('i')
    30                        .conflicts_with("search")
    31                        .help("view package information")
    32                        .action(ArgAction::Set)
    33                        .num_args(1..),
    34                ),
    35        )
    36        // Sync subcommand
    37        //
    38        // Only a few of its arguments are implemented below.
    39        .subcommand(
    40            Command::new("sync")
    41                .short_flag('S')
    42                .long_flag("sync")
    43                .about("Synchronize packages.")
    44                .arg(
    45                    Arg::new("search")
    46                        .short('s')
    47                        .long("search")
    48                        .conflicts_with("info")
    49                        .action(ArgAction::Set)
    50                        .num_args(1..)
    51                        .help("search remote repositories for matching strings"),
    52                )
    53                .arg(
    54                    Arg::new("info")
    55                        .long("info")
    56                        .conflicts_with("search")
    57                        .short('i')
    58                        .action(ArgAction::SetTrue)
    59                        .help("view package information"),
    60                )
    61                .arg(
    62                    Arg::new("package")
    63                        .help("packages")
    64                        .required_unless_present("search")
    65                        .action(ArgAction::Set)
    66                        .num_args(1..),
    67                ),
    68        )
    69}

Source

#### pub fn alias(self, name: impl IntoResettable<Str>) -> Command

Sets a hidden alias to this subcommand.

This allows the subcommand to be accessed via either the original name, or this given alias. This is more efficient and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all aliased variants.

NOTE: Aliases defined with this method are hidden from the help message. If you’re looking for aliases that will be displayed in the help message, see `Command::visible_alias`.

NOTE: When using aliases and checking for the existence of a particular subcommand within an `ArgMatches` struct, one only needs to search for the original name and not all aliases.

##### §Examples

    let m = Command::new("myprog")
        .subcommand(Command::new("test")
            .alias("do-stuff"))
        .get_matches_from(vec!["myprog", "do-stuff"]);
    assert_eq!(m.subcommand_name(), Some("test"));

##### Examples found in repository?

examples/repl.rs (line 78)

    51fn cli() -> Command {
    52    // strip out usage
    53    const PARSER_TEMPLATE: &str = "\
    54        {all-args}
    55    ";
    56    // strip out name/version
    57    const APPLET_TEMPLATE: &str = "\
    58        {about-with-newline}\n\
    59        {usage-heading}\n    {usage}\n\
    60        \n\
    61        {all-args}{after-help}\
    62    ";
    63
    64    Command::new("repl")
    65        .multicall(true)
    66        .arg_required_else_help(true)
    67        .subcommand_required(true)
    68        .subcommand_value_name("APPLET")
    69        .subcommand_help_heading("APPLETS")
    70        .help_template(PARSER_TEMPLATE)
    71        .subcommand(
    72            Command::new("ping")
    73                .about("Get a response")
    74                .help_template(APPLET_TEMPLATE),
    75        )
    76        .subcommand(
    77            Command::new("quit")
    78                .alias("exit")
    79                .about("Quit the REPL")
    80                .help_template(APPLET_TEMPLATE),
    81        )
    82}

Source

#### pub fn short_flag_alias(self, name: impl IntoResettable<char>) -> Command

Add an alias, which functions as “hidden” short flag subcommand

This will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.

##### §Examples

    let m = Command::new("myprog")
                .subcommand(Command::new("test").short_flag('t')
                    .short_flag_alias('d'))
                .get_matches_from(vec!["myprog", "-d"]);
    assert_eq!(m.subcommand_name(), Some("test"));

Source

#### pub fn long_flag_alias(self, name: impl IntoResettable<Str>) -> Command

Add an alias, which functions as a “hidden” long flag subcommand.

This will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.

##### §Examples

    let m = Command::new("myprog")
                .subcommand(Command::new("test").long_flag("test")
                    .long_flag_alias("testing"))
                .get_matches_from(vec!["myprog", "--testing"]);
    assert_eq!(m.subcommand_name(), Some("test"));

Source

#### pub fn aliases(self, names: impl IntoIterator<Item = impl Into<Str>>) -> Command

Sets multiple hidden aliases to this subcommand.

This allows the subcommand to be accessed via either the original name or any of the given aliases. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command and not all aliased variants.

NOTE: Aliases defined with this method are hidden from the help message. If looking for aliases that will be displayed in the help message, see `Command::visible_aliases`.

NOTE: When using aliases and checking for the existence of a particular subcommand within an `ArgMatches` struct, one only needs to search for the original name and not all aliases.

##### §Examples

    let m = Command::new("myprog")
        .subcommand(Command::new("test")
            .aliases(["do-stuff", "do-tests", "tests"]))
            .arg(Arg::new("input")
                .help("the file to add")
                .required(false))
        .get_matches_from(vec!["myprog", "do-tests"]);
    assert_eq!(m.subcommand_name(), Some("test"));

Source

#### pub fn short_flag_aliases( self, names: impl IntoIterator<Item = char>, ) -> Command

Add aliases, which function as “hidden” short flag subcommands.

These will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.

##### §Examples

    let m = Command::new("myprog")
        .subcommand(Command::new("test").short_flag('t')
            .short_flag_aliases(['a', 'b', 'c']))
            .arg(Arg::new("input")
                .help("the file to add")
                .required(false))
        .get_matches_from(vec!["myprog", "-a"]);
    assert_eq!(m.subcommand_name(), Some("test"));

Source

#### pub fn long_flag_aliases( self, names: impl IntoIterator<Item = impl Into<Str>>, ) -> Command

Add aliases, which function as “hidden” long flag subcommands.

These will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.

##### §Examples

    let m = Command::new("myprog")
                .subcommand(Command::new("test").long_flag("test")
                    .long_flag_aliases(["testing", "testall", "test_all"]))
                    .arg(Arg::new("input")
                                .help("the file to add")
                                .required(false))
                .get_matches_from(vec!["myprog", "--testing"]);
    assert_eq!(m.subcommand_name(), Some("test"));

Source

#### pub fn visible_alias(self, name: impl IntoResettable<Str>) -> Command

Sets a visible alias to this subcommand.

This allows the subcommand to be accessed via either the original name or the given alias. This is more efficient and easier than creating hidden subcommands as one only needs to check for the existence of this command and not all aliased variants.

NOTE: The alias defined with this method is visible from the help message and displayed as if it were just another regular subcommand. If looking for an alias that will not be displayed in the help message, see `Command::alias`.

NOTE: When using aliases and checking for the existence of a particular subcommand within an `ArgMatches` struct, one only needs to search for the original name and not all aliases.

##### §Examples

    let m = Command::new("myprog")
        .subcommand(Command::new("test")
            .visible_alias("do-stuff"))
        .get_matches_from(vec!["myprog", "do-stuff"]);
    assert_eq!(m.subcommand_name(), Some("test"));

Source

#### pub fn visible_short_flag_alias( self, name: impl IntoResettable<char>, ) -> Command

Add an alias, which functions as “visible” short flag subcommand

This will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.

See also `Command::short_flag_alias`.

##### §Examples

    let m = Command::new("myprog")
                .subcommand(Command::new("test").short_flag('t')
                    .visible_short_flag_alias('d'))
                .get_matches_from(vec!["myprog", "-d"]);
    assert_eq!(m.subcommand_name(), Some("test"));

Source

#### pub fn visible_long_flag_alias(self, name: impl IntoResettable<Str>) -> Command

Add an alias, which functions as a “visible” long flag subcommand.

This will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.

See also `Command::long_flag_alias`.

##### §Examples

    let m = Command::new("myprog")
                .subcommand(Command::new("test").long_flag("test")
                    .visible_long_flag_alias("testing"))
                .get_matches_from(vec!["myprog", "--testing"]);
    assert_eq!(m.subcommand_name(), Some("test"));

Source

#### pub fn visible_aliases( self, names: impl IntoIterator<Item = impl Into<Str>>, ) -> Command

Sets multiple visible aliases to this subcommand.

This allows the subcommand to be accessed via either the original name or any of the given aliases. This is more efficient and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command and not all aliased variants.

NOTE: The alias defined with this method is visible from the help message and displayed as if it were just another regular subcommand. If looking for an alias that will not be displayed in the help message, see `Command::alias`.

NOTE: When using aliases, and checking for the existence of a particular subcommand within an `ArgMatches` struct, one only needs to search for the original name and not all aliases.

##### §Examples

    let m = Command::new("myprog")
        .subcommand(Command::new("test")
            .visible_aliases(["do-stuff", "tests"]))
        .get_matches_from(vec!["myprog", "do-stuff"]);
    assert_eq!(m.subcommand_name(), Some("test"));

Source

#### pub fn visible_short_flag_aliases( self, names: impl IntoIterator<Item = char>, ) -> Command

Add aliases, which function as visible short flag subcommands.

See `Command::short_flag_aliases`.

##### §Examples

    let m = Command::new("myprog")
                .subcommand(Command::new("test").short_flag('b')
                    .visible_short_flag_aliases(['t']))
                .get_matches_from(vec!["myprog", "-t"]);
    assert_eq!(m.subcommand_name(), Some("test"));

Source

#### pub fn visible_long_flag_aliases( self, names: impl IntoIterator<Item = impl Into<Str>>, ) -> Command

Add aliases, which function as visible long flag subcommands.

See `Command::long_flag_aliases`.

##### §Examples

    let m = Command::new("myprog")
                .subcommand(Command::new("test").long_flag("test")
                    .visible_long_flag_aliases(["testing", "testall", "test_all"]))
                .get_matches_from(vec!["myprog", "--testing"]);
    assert_eq!(m.subcommand_name(), Some("test"));

Source

#### pub fn display_order(self, ord: impl IntoResettable<usize>) -> Command

Set the placement of this subcommand within the help.

Subcommands with a lower value will be displayed first in the help message. Those with the same display order will be sorted.

`Command`s are automatically assigned a display order based on the order they are added to their parent `Command`. Overriding this is helpful when the order commands are added in isn’t the same as the display order, whether in one-off cases or to automatically sort commands.

##### §Examples

    let m = Command::new("cust-ord")
        .subcommand(Command::new("beta")
            .display_order(0)  // Sort
            .about("Some help and text"))
        .subcommand(Command::new("alpha")
            .display_order(0)  // Sort
            .about("I should be first!"))
        .get_matches_from(vec![
            "cust-ord", "--help"
        ]);

The above example displays the following help message

    cust-ord

    Usage: cust-ord [OPTIONS]

    Commands:
        alpha    I should be first!
        beta     Some help and text
        help     Print help for the subcommand(s)

    Options:
        -h, --help       Print help
        -V, --version    Print version

Source

#### pub fn hide(self, yes: bool) -> Command

Specifies that this `subcommand` should be hidden from help messages

##### §Examples

    Command::new("myprog")
        .subcommand(
            Command::new("test").hide(true)
        )

Source

#### pub fn subcommand_required(self, yes: bool) -> Command

If no `subcommand` is present at runtime, error and exit gracefully.

##### §Examples

    let err = Command::new("myprog")
        .subcommand_required(true)
        .subcommand(Command::new("test"))
        .try_get_matches_from(vec![
            "myprog",
        ]);
    assert!(err.is_err());
    assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand);

##### Examples found in repository?

examples/derive_ref/hand_subcommand.rs (line 57)

    54    fn augment_subcommands(cmd: Command) -> Command {
    55        cmd.subcommand(AddArgs::augment_args(Command::new("add")))
    56            .subcommand(RemoveArgs::augment_args(Command::new("remove")))
    57            .subcommand_required(true)
    58    }
    59    fn augment_subcommands_for_update(cmd: Command) -> Command {
    60        cmd.subcommand(AddArgs::augment_args(Command::new("add")))
    61            .subcommand(RemoveArgs::augment_args(Command::new("remove")))
    62            .subcommand_required(true)
    63    }

More examples
Hide additional examples
examples/repl.rs (line 67)

    51fn cli() -> Command {
    52    // strip out usage
    53    const PARSER_TEMPLATE: &str = "\
    54        {all-args}
    55    ";
    56    // strip out name/version
    57    const APPLET_TEMPLATE: &str = "\
    58        {about-with-newline}\n\
    59        {usage-heading}\n    {usage}\n\
    60        \n\
    61        {all-args}{after-help}\
    62    ";
    63
    64    Command::new("repl")
    65        .multicall(true)
    66        .arg_required_else_help(true)
    67        .subcommand_required(true)
    68        .subcommand_value_name("APPLET")
    69        .subcommand_help_heading("APPLETS")
    70        .help_template(PARSER_TEMPLATE)
    71        .subcommand(
    72            Command::new("ping")
    73                .about("Get a response")
    74                .help_template(APPLET_TEMPLATE),
    75        )
    76        .subcommand(
    77            Command::new("quit")
    78                .alias("exit")
    79                .about("Quit the REPL")
    80                .help_template(APPLET_TEMPLATE),
    81        )
    82}

examples/git.rs (line 9)

    6fn cli() -> Command {
    7    Command::new("git")
    8        .about("A fictional versioning CLI")
    9        .subcommand_required(true)
    10        .arg_required_else_help(true)
    11        .allow_external_subcommands(true)
    12        .subcommand(
    13            Command::new("clone")
    14                .about("Clones repos")
    15                .arg(arg!(<REMOTE> "The remote to clone"))
    16                .arg_required_else_help(true),
    17        )
    18        .subcommand(
    19            Command::new("diff")
    20                .about("Compare two commits")
    21                .arg(arg!(base: [COMMIT]))
    22                .arg(arg!(head: [COMMIT]))
    23                .arg(arg!(path: [PATH]).last(true))
    24                .arg(
    25                    arg!(--color <WHEN>)
    26                        .value_parser(["always", "auto", "never"])
    27                        .num_args(0..=1)
    28                        .require_equals(true)
    29                        .default_value("auto")
    30                        .default_missing_value("always"),
    31                ),
    32        )
    33        .subcommand(
    34            Command::new("push")
    35                .about("pushes things")
    36                .arg(arg!(<REMOTE> "The remote to target"))
    37                .arg_required_else_help(true),
    38        )
    39        .subcommand(
    40            Command::new("add")
    41                .about("adds things")
    42                .arg_required_else_help(true)
    43                .arg(arg!(<PATH> ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))),
    44        )
    45        .subcommand(
    46            Command::new("stash")
    47                .args_conflicts_with_subcommands(true)
    48                .flatten_help(true)
    49                .args(push_args())
    50                .subcommand(Command::new("push").args(push_args()))
    51                .subcommand(Command::new("pop").arg(arg!([STASH])))
    52                .subcommand(Command::new("apply").arg(arg!([STASH]))),
    53        )
    54}

examples/pacman.rs (line 7)

    3fn cli() -> Command {
    4    Command::new("pacman")
    5        .about("package manager utility")
    6        .version("5.2.1")
    7        .subcommand_required(true)
    8        .arg_required_else_help(true)
    9        // Query subcommand
    10        //
    11        // Only a few of its arguments are implemented below.
    12        .subcommand(
    13            Command::new("query")
    14                .short_flag('Q')
    15                .long_flag("query")
    16                .about("Query the package database.")
    17                .arg(
    18                    Arg::new("search")
    19                        .short('s')
    20                        .long("search")
    21                        .help("search locally installed packages for matching strings")
    22                        .conflicts_with("info")
    23                        .action(ArgAction::Set)
    24                        .num_args(1..),
    25                )
    26                .arg(
    27                    Arg::new("info")
    28                        .long("info")
    29                        .short('i')
    30                        .conflicts_with("search")
    31                        .help("view package information")
    32                        .action(ArgAction::Set)
    33                        .num_args(1..),
    34                ),
    35        )
    36        // Sync subcommand
    37        //
    38        // Only a few of its arguments are implemented below.
    39        .subcommand(
    40            Command::new("sync")
    41                .short_flag('S')
    42                .long_flag("sync")
    43                .about("Synchronize packages.")
    44                .arg(
    45                    Arg::new("search")
    46                        .short('s')
    47                        .long("search")
    48                        .conflicts_with("info")
    49                        .action(ArgAction::Set)
    50                        .num_args(1..)
    51                        .help("search remote repositories for matching strings"),
    52                )
    53                .arg(
    54                    Arg::new("info")
    55                        .long("info")
    56                        .conflicts_with("search")
    57                        .short('i')
    58                        .action(ArgAction::SetTrue)
    59                        .help("view package information"),
    60                )
    61                .arg(
    62                    Arg::new("package")
    63                        .help("packages")
    64                        .required_unless_present("search")
    65                        .action(ArgAction::Set)
    66                        .num_args(1..),
    67                ),
    68        )
    69}

Source

#### pub fn allow_external_subcommands(self, yes: bool) -> Command

Assume unexpected positional arguments are a `subcommand`.

Arguments will be stored in the `""` argument in the `ArgMatches`

NOTE: Use this setting with caution, as a truly unexpected argument (i.e. one that is NOT an external subcommand) will not cause an error and instead be treated as a potential subcommand. One should check for such cases manually and inform the user appropriately.

NOTE: A built-in subcommand will be parsed as an external subcommand when escaped with `--`.

##### §Examples

    // Assume there is an external subcommand named "subcmd"
    let m = Command::new("myprog")
        .allow_external_subcommands(true)
        .get_matches_from(vec![
            "myprog", "subcmd", "--option", "value", "-fff", "--flag"
        ]);

    // All trailing arguments will be stored under the subcommand's sub-matches using an empty
    // string argument name
    match m.subcommand() {
        Some((external, ext_m)) => {
             let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect();
             assert_eq!(external, "subcmd");
             assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
        },
        _ => {},
    }

##### Examples found in repository?

examples/git.rs (line 11)

    6fn cli() -> Command {
    7    Command::new("git")
    8        .about("A fictional versioning CLI")
    9        .subcommand_required(true)
    10        .arg_required_else_help(true)
    11        .allow_external_subcommands(true)
    12        .subcommand(
    13            Command::new("clone")
    14                .about("Clones repos")
    15                .arg(arg!(<REMOTE> "The remote to clone"))
    16                .arg_required_else_help(true),
    17        )
    18        .subcommand(
    19            Command::new("diff")
    20                .about("Compare two commits")
    21                .arg(arg!(base: [COMMIT]))
    22                .arg(arg!(head: [COMMIT]))
    23                .arg(arg!(path: [PATH]).last(true))
    24                .arg(
    25                    arg!(--color <WHEN>)
    26                        .value_parser(["always", "auto", "never"])
    27                        .num_args(0..=1)
    28                        .require_equals(true)
    29                        .default_value("auto")
    30                        .default_missing_value("always"),
    31                ),
    32        )
    33        .subcommand(
    34            Command::new("push")
    35                .about("pushes things")
    36                .arg(arg!(<REMOTE> "The remote to target"))
    37                .arg_required_else_help(true),
    38        )
    39        .subcommand(
    40            Command::new("add")
    41                .about("adds things")
    42                .arg_required_else_help(true)
    43                .arg(arg!(<PATH> ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))),
    44        )
    45        .subcommand(
    46            Command::new("stash")
    47                .args_conflicts_with_subcommands(true)
    48                .flatten_help(true)
    49                .args(push_args())
    50                .subcommand(Command::new("push").args(push_args()))
    51                .subcommand(Command::new("pop").arg(arg!([STASH])))
    52                .subcommand(Command::new("apply").arg(arg!([STASH]))),
    53        )
    54}

Source

#### pub fn external_subcommand_value_parser( self, parser: impl IntoResettable<ValueParser>, ) -> Command

Specifies how to parse external subcommand arguments.

The default parser is for `OsString`. This can be used to switch it to `String` or another type.

NOTE: Setting this requires `Command::allow_external_subcommands`

##### §Examples

    // Assume there is an external subcommand named "subcmd"
    let m = Command::new("myprog")
        .allow_external_subcommands(true)
        .get_matches_from(vec![
            "myprog", "subcmd", "--option", "value", "-fff", "--flag"
        ]);

    // All trailing arguments will be stored under the subcommand's sub-matches using an empty
    // string argument name
    match m.subcommand() {
        Some((external, ext_m)) => {
             let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect();
             assert_eq!(external, "subcmd");
             assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
        },
        _ => {},
    }

    // Assume there is an external subcommand named "subcmd"
    let m = Command::new("myprog")
        .external_subcommand_value_parser(value_parser!(String))
        .get_matches_from(vec![
            "myprog", "subcmd", "--option", "value", "-fff", "--flag"
        ]);

    // All trailing arguments will be stored under the subcommand's sub-matches using an empty
    // string argument name
    match m.subcommand() {
        Some((external, ext_m)) => {
             let ext_args: Vec<_> = ext_m.get_many::<String>("").unwrap().collect();
             assert_eq!(external, "subcmd");
             assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
        },
        _ => {},
    }

Source

#### pub fn args_conflicts_with_subcommands(self, yes: bool) -> Command

Specifies that use of an argument prevents the use of `subcommands`.

By default `clap` allows arguments between subcommands such as `<cmd> [cmd_args] <subcmd> [subcmd_args] <subsubcmd> [subsubcmd_args]`.

This setting disables that functionality and says that arguments can only follow the final subcommand. For instance using this setting makes only the following invocations possible:

- `<cmd> <subcmd> <subsubcmd> [subsubcmd_args]`
- `<cmd> <subcmd> [subcmd_args]`
- `<cmd> [cmd_args]`

##### §Examples

    Command::new("myprog")
        .args_conflicts_with_subcommands(true);

##### Examples found in repository?

examples/git.rs (line 47)

    6fn cli() -> Command {
    7    Command::new("git")
    8        .about("A fictional versioning CLI")
    9        .subcommand_required(true)
    10        .arg_required_else_help(true)
    11        .allow_external_subcommands(true)
    12        .subcommand(
    13            Command::new("clone")
    14                .about("Clones repos")
    15                .arg(arg!(<REMOTE> "The remote to clone"))
    16                .arg_required_else_help(true),
    17        )
    18        .subcommand(
    19            Command::new("diff")
    20                .about("Compare two commits")
    21                .arg(arg!(base: [COMMIT]))
    22                .arg(arg!(head: [COMMIT]))
    23                .arg(arg!(path: [PATH]).last(true))
    24                .arg(
    25                    arg!(--color <WHEN>)
    26                        .value_parser(["always", "auto", "never"])
    27                        .num_args(0..=1)
    28                        .require_equals(true)
    29                        .default_value("auto")
    30                        .default_missing_value("always"),
    31                ),
    32        )
    33        .subcommand(
    34            Command::new("push")
    35                .about("pushes things")
    36                .arg(arg!(<REMOTE> "The remote to target"))
    37                .arg_required_else_help(true),
    38        )
    39        .subcommand(
    40            Command::new("add")
    41                .about("adds things")
    42                .arg_required_else_help(true)
    43                .arg(arg!(<PATH> ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))),
    44        )
    45        .subcommand(
    46            Command::new("stash")
    47                .args_conflicts_with_subcommands(true)
    48                .flatten_help(true)
    49                .args(push_args())
    50                .subcommand(Command::new("push").args(push_args()))
    51                .subcommand(Command::new("pop").arg(arg!([STASH])))
    52                .subcommand(Command::new("apply").arg(arg!([STASH]))),
    53        )
    54}

Source

#### pub fn subcommand_precedence_over_arg(self, yes: bool) -> Command

Prevent subcommands from being consumed as an arguments value.

By default, if an option taking multiple values is followed by a subcommand, the subcommand will be parsed as another value.

    cmd --foo val1 val2 subcommand
              --------- ----------
                values   another value

This setting instructs the parser to stop when encountering a subcommand instead of greedily consuming arguments.

    cmd --foo val1 val2 subcommand
              --------- ----------
                values   subcommand

##### §Examples

    let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg(
        Arg::new("arg")
            .long("arg")
            .num_args(1..)
            .action(ArgAction::Set),
    );

    let matches = cmd
        .clone()
        .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
        .unwrap();
    assert_eq!(
        matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(),
        &["1", "2", "3", "sub"]
    );
    assert!(matches.subcommand_matches("sub").is_none());

    let matches = cmd
        .subcommand_precedence_over_arg(true)
        .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
        .unwrap();
    assert_eq!(
        matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(),
        &["1", "2", "3"]
    );
    assert!(matches.subcommand_matches("sub").is_some());

Source

#### pub fn subcommand_negates_reqs(self, yes: bool) -> Command

Allows `subcommands` to override all requirements of the parent command.

For example, if you had a subcommand or top level application with a required argument that is only required as long as there is no subcommand present, using this setting would allow you to set those arguments to `Arg::required(true)` and yet receive no error so long as the user uses a valid subcommand instead.

NOTE: This defaults to false (using subcommand does not negate requirements)

##### §Examples

This first example shows that it is an error to not use a required argument

    let err = Command::new("myprog")
        .subcommand_negates_reqs(true)
        .arg(Arg::new("opt").required(true))
        .subcommand(Command::new("test"))
        .try_get_matches_from(vec![
            "myprog"
        ]);
    assert!(err.is_err());
    assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);

This next example shows that it is no longer error to not use a required argument if a valid subcommand is used.

    let noerr = Command::new("myprog")
        .subcommand_negates_reqs(true)
        .arg(Arg::new("opt").required(true))
        .subcommand(Command::new("test"))
        .try_get_matches_from(vec![
            "myprog", "test"
        ]);
    assert!(noerr.is_ok());

Source

#### pub fn multicall(self, yes: bool) -> Command

Multiple-personality program dispatched on the binary name (`argv[0]`)

A “multicall” executable is a single executable that contains a variety of applets, and decides which applet to run based on the name of the file. The executable can be called from different names by creating hard links or symbolic links to it.

This is desirable for:

- Easy distribution, a single binary that can install hardlinks to access the different personalities.
- Minimal binary size by sharing common code (e.g. standard library, clap)
- Custom shells or REPLs where there isn’t a single top-level command

Setting `multicall` will cause

- `argv[0]` to be stripped to the base name and parsed as the first argument, as if `Command::no_binary_name` was set.
- Help and errors to report subcommands as if they were the top-level command

When the subcommand is not present, there are several strategies you may employ, depending on your needs:

- Let the error percolate up normally
- Print a specialized error message using the `Error::context`
- Print the help but this might be ambiguous
- Disable `multicall` and re-parse it
- Disable `multicall` and re-parse it with a specific subcommand

When detecting the error condition, the `ErrorKind` isn’t sufficient as a sub-subcommand might report the same error. Enable `allow_external_subcommands` if you want to specifically get the unrecognized binary name.

NOTE: Multicall can’t be used with `no_binary_name` since they interpret the command name in incompatible ways.

NOTE: The multicall command cannot have arguments.

NOTE: Applets are slightly semantically different from subcommands, so it’s recommended to use `Command::subcommand_help_heading` and `Command::subcommand_value_name` to change the descriptive text as above.

##### §Examples

`hostname` is an example of a multicall executable. Both `hostname` and `dnsdomainname` are provided by the same executable and which behaviour to use is based on the executable file name.

This is desirable when the executable has a primary purpose but there is related functionality that would be convenient to provide and implement it to be in the same executable.

The name of the cmd is essentially unused and may be the same as the name of a subcommand.

The names of the immediate subcommands of the Command are matched against the basename of the first argument, which is conventionally the path of the executable.

This does not allow the subcommand to be passed as the first non-path argument.

    let mut cmd = Command::new("hostname")
        .multicall(true)
        .subcommand(Command::new("hostname"))
        .subcommand(Command::new("dnsdomainname"));
    let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]);
    assert!(m.is_err());
    assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument);
    let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]);
    assert_eq!(m.subcommand_name(), Some("dnsdomainname"));

Busybox is another common example of a multicall executable with a subcommmand for each applet that can be run directly, e.g. with the `cat` applet being run by running `busybox cat`, or with `cat` as a link to the `busybox` binary.

This is desirable when the launcher program has additional options or it is useful to run the applet without installing a symlink e.g. to test the applet without installing it or there may already be a command of that name installed.

To make an applet usable as both a multicall link and a subcommand the subcommands must be defined both in the top-level Command and as subcommands of the “main” applet.

    fn applet_commands() -> [Command; 2] {
        [Command::new("true"), Command::new("false")]
    }
    let mut cmd = Command::new("busybox")
        .multicall(true)
        .subcommand(
            Command::new("busybox")
                .subcommand_value_name("APPLET")
                .subcommand_help_heading("APPLETS")
                .subcommands(applet_commands()),
        )
        .subcommands(applet_commands());
    // When called from the executable's canonical name
    // its applets can be matched as subcommands.
    let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap();
    assert_eq!(m.subcommand_name(), Some("busybox"));
    assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true"));
    // When called from a link named after an applet that applet is matched.
    let m = cmd.get_matches_from(&["/usr/bin/true"]);
    assert_eq!(m.subcommand_name(), Some("true"));

##### Examples found in repository?

examples/multicall-hostname.rs (line 5)

    3fn main() {
    4    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    5        .multicall(true)
    6        .arg_required_else_help(true)
    7        .subcommand_value_name("APPLET")
    8        .subcommand_help_heading("APPLETS")
    9        .subcommand(Command::new("hostname").about("show hostname part of FQDN"))
    10        .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN"));
    11
    12    match cmd.get_matches().subcommand_name() {
    13        Some("hostname") => println!("www"),
    14        Some("dnsdomainname") => println!("example.com"),
    15        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    16    }
    17}

More examples
Hide additional examples
examples/repl.rs (line 65)

    51fn cli() -> Command {
    52    // strip out usage
    53    const PARSER_TEMPLATE: &str = "\
    54        {all-args}
    55    ";
    56    // strip out name/version
    57    const APPLET_TEMPLATE: &str = "\
    58        {about-with-newline}\n\
    59        {usage-heading}\n    {usage}\n\
    60        \n\
    61        {all-args}{after-help}\
    62    ";
    63
    64    Command::new("repl")
    65        .multicall(true)
    66        .arg_required_else_help(true)
    67        .subcommand_required(true)
    68        .subcommand_value_name("APPLET")
    69        .subcommand_help_heading("APPLETS")
    70        .help_template(PARSER_TEMPLATE)
    71        .subcommand(
    72            Command::new("ping")
    73                .about("Get a response")
    74                .help_template(APPLET_TEMPLATE),
    75        )
    76        .subcommand(
    77            Command::new("quit")
    78                .alias("exit")
    79                .about("Quit the REPL")
    80                .help_template(APPLET_TEMPLATE),
    81        )
    82}

examples/multicall-busybox.rs (line 15)

    13fn main() {
    14    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    15        .multicall(true)
    16        .subcommand(
    17            Command::new("busybox")
    18                .arg_required_else_help(true)
    19                .subcommand_value_name("APPLET")
    20                .subcommand_help_heading("APPLETS")
    21                .arg(
    22                    Arg::new("install")
    23                        .long("install")
    24                        .help("Install hardlinks for all subcommands in path")
    25                        .exclusive(true)
    26                        .action(ArgAction::Set)
    27                        .default_missing_value("/usr/local/bin")
    28                        .value_parser(value_parser!(PathBuf)),
    29                )
    30                .subcommands(applet_commands()),
    31        )
    32        .subcommands(applet_commands());
    33
    34    let matches = cmd.get_matches();
    35    let mut subcommand = matches.subcommand();
    36    if let Some(("busybox", cmd)) = subcommand {
    37        if cmd.contains_id("install") {
    38            unimplemented!("Make hardlinks to the executable here");
    39        }
    40        subcommand = cmd.subcommand();
    41    }
    42    match subcommand {
    43        Some(("false", _)) => exit(1),
    44        Some(("true", _)) => exit(0),
    45        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    46    }
    47}

Source

#### pub fn subcommand_value_name( self, value_name: impl IntoResettable<Str>, ) -> Command

Sets the value name used for subcommands when printing usage and help.

By default, this is “COMMAND”.

See also `Command::subcommand_help_heading`

##### §Examples

    Command::new("myprog")
        .subcommand(Command::new("sub1"))
        .print_help()

will produce

    myprog

    Usage: myprog [COMMAND]

    Commands:
        help    Print this message or the help of the given subcommand(s)
        sub1

    Options:
        -h, --help       Print help
        -V, --version    Print version

but usage of `subcommand_value_name`

    Command::new("myprog")
        .subcommand(Command::new("sub1"))
        .subcommand_value_name("THING")
        .print_help()

will produce

    myprog

    Usage: myprog [THING]

    Commands:
        help    Print this message or the help of the given subcommand(s)
        sub1

    Options:
        -h, --help       Print help
        -V, --version    Print version

##### Examples found in repository?

examples/multicall-hostname.rs (line 7)

    3fn main() {
    4    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    5        .multicall(true)
    6        .arg_required_else_help(true)
    7        .subcommand_value_name("APPLET")
    8        .subcommand_help_heading("APPLETS")
    9        .subcommand(Command::new("hostname").about("show hostname part of FQDN"))
    10        .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN"));
    11
    12    match cmd.get_matches().subcommand_name() {
    13        Some("hostname") => println!("www"),
    14        Some("dnsdomainname") => println!("example.com"),
    15        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    16    }
    17}

More examples
Hide additional examples
examples/repl.rs (line 68)

    51fn cli() -> Command {
    52    // strip out usage
    53    const PARSER_TEMPLATE: &str = "\
    54        {all-args}
    55    ";
    56    // strip out name/version
    57    const APPLET_TEMPLATE: &str = "\
    58        {about-with-newline}\n\
    59        {usage-heading}\n    {usage}\n\
    60        \n\
    61        {all-args}{after-help}\
    62    ";
    63
    64    Command::new("repl")
    65        .multicall(true)
    66        .arg_required_else_help(true)
    67        .subcommand_required(true)
    68        .subcommand_value_name("APPLET")
    69        .subcommand_help_heading("APPLETS")
    70        .help_template(PARSER_TEMPLATE)
    71        .subcommand(
    72            Command::new("ping")
    73                .about("Get a response")
    74                .help_template(APPLET_TEMPLATE),
    75        )
    76        .subcommand(
    77            Command::new("quit")
    78                .alias("exit")
    79                .about("Quit the REPL")
    80                .help_template(APPLET_TEMPLATE),
    81        )
    82}

examples/multicall-busybox.rs (line 19)

    13fn main() {
    14    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    15        .multicall(true)
    16        .subcommand(
    17            Command::new("busybox")
    18                .arg_required_else_help(true)
    19                .subcommand_value_name("APPLET")
    20                .subcommand_help_heading("APPLETS")
    21                .arg(
    22                    Arg::new("install")
    23                        .long("install")
    24                        .help("Install hardlinks for all subcommands in path")
    25                        .exclusive(true)
    26                        .action(ArgAction::Set)
    27                        .default_missing_value("/usr/local/bin")
    28                        .value_parser(value_parser!(PathBuf)),
    29                )
    30                .subcommands(applet_commands()),
    31        )
    32        .subcommands(applet_commands());
    33
    34    let matches = cmd.get_matches();
    35    let mut subcommand = matches.subcommand();
    36    if let Some(("busybox", cmd)) = subcommand {
    37        if cmd.contains_id("install") {
    38            unimplemented!("Make hardlinks to the executable here");
    39        }
    40        subcommand = cmd.subcommand();
    41    }
    42    match subcommand {
    43        Some(("false", _)) => exit(1),
    44        Some(("true", _)) => exit(0),
    45        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    46    }
    47}

Source

#### pub fn subcommand_help_heading( self, heading: impl IntoResettable<Str>, ) -> Command

Sets the help heading used for subcommands when printing usage and help.

By default, this is “Commands”.

See also `Command::subcommand_value_name`

##### §Examples

    Command::new("myprog")
        .subcommand(Command::new("sub1"))
        .print_help()

will produce

    myprog

    Usage: myprog [COMMAND]

    Commands:
        help    Print this message or the help of the given subcommand(s)
        sub1

    Options:
        -h, --help       Print help
        -V, --version    Print version

but usage of `subcommand_help_heading`

    Command::new("myprog")
        .subcommand(Command::new("sub1"))
        .subcommand_help_heading("Things")
        .print_help()

will produce

    myprog

    Usage: myprog [COMMAND]

    Things:
        help    Print this message or the help of the given subcommand(s)
        sub1

    Options:
        -h, --help       Print help
        -V, --version    Print version

##### Examples found in repository?

examples/multicall-hostname.rs (line 8)

    3fn main() {
    4    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    5        .multicall(true)
    6        .arg_required_else_help(true)
    7        .subcommand_value_name("APPLET")
    8        .subcommand_help_heading("APPLETS")
    9        .subcommand(Command::new("hostname").about("show hostname part of FQDN"))
    10        .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN"));
    11
    12    match cmd.get_matches().subcommand_name() {
    13        Some("hostname") => println!("www"),
    14        Some("dnsdomainname") => println!("example.com"),
    15        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    16    }
    17}

More examples
Hide additional examples
examples/repl.rs (line 69)

    51fn cli() -> Command {
    52    // strip out usage
    53    const PARSER_TEMPLATE: &str = "\
    54        {all-args}
    55    ";
    56    // strip out name/version
    57    const APPLET_TEMPLATE: &str = "\
    58        {about-with-newline}\n\
    59        {usage-heading}\n    {usage}\n\
    60        \n\
    61        {all-args}{after-help}\
    62    ";
    63
    64    Command::new("repl")
    65        .multicall(true)
    66        .arg_required_else_help(true)
    67        .subcommand_required(true)
    68        .subcommand_value_name("APPLET")
    69        .subcommand_help_heading("APPLETS")
    70        .help_template(PARSER_TEMPLATE)
    71        .subcommand(
    72            Command::new("ping")
    73                .about("Get a response")
    74                .help_template(APPLET_TEMPLATE),
    75        )
    76        .subcommand(
    77            Command::new("quit")
    78                .alias("exit")
    79                .about("Quit the REPL")
    80                .help_template(APPLET_TEMPLATE),
    81        )
    82}

examples/multicall-busybox.rs (line 20)

    13fn main() {
    14    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
    15        .multicall(true)
    16        .subcommand(
    17            Command::new("busybox")
    18                .arg_required_else_help(true)
    19                .subcommand_value_name("APPLET")
    20                .subcommand_help_heading("APPLETS")
    21                .arg(
    22                    Arg::new("install")
    23                        .long("install")
    24                        .help("Install hardlinks for all subcommands in path")
    25                        .exclusive(true)
    26                        .action(ArgAction::Set)
    27                        .default_missing_value("/usr/local/bin")
    28                        .value_parser(value_parser!(PathBuf)),
    29                )
    30                .subcommands(applet_commands()),
    31        )
    32        .subcommands(applet_commands());
    33
    34    let matches = cmd.get_matches();
    35    let mut subcommand = matches.subcommand();
    36    if let Some(("busybox", cmd)) = subcommand {
    37        if cmd.contains_id("install") {
    38            unimplemented!("Make hardlinks to the executable here");
    39        }
    40        subcommand = cmd.subcommand();
    41    }
    42    match subcommand {
    43        Some(("false", _)) => exit(1),
    44        Some(("true", _)) => exit(0),
    45        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    46    }
    47}

Source§

### impl Command

#### §Reflection

Source

#### pub fn get_display_name(&self) -> Option<&str>

Get the name of the binary.

Source

#### pub fn get_bin_name(&self) -> Option<&str>

Get the name of the binary.

Source

#### pub fn set_bin_name(&mut self, name: impl Into<String>)

Set binary name. Uses `&mut self` instead of `self`.

Source

#### pub fn get_name(&self) -> &str

Get the name of the cmd.

Source

#### pub fn get_name_and_visible_aliases(&self) -> Vec<&str>

Get all known names of the cmd (i.e. primary name and visible aliases).

Source

#### pub fn get_version(&self) -> Option<&str>

Get the version of the cmd.

Source

#### pub fn get_long_version(&self) -> Option<&str>

Get the long version of the cmd.

Source

#### pub fn get_display_order(&self) -> usize

Get the placement within help

Source

#### pub fn get_author(&self) -> Option<&str>

Get the authors of the cmd.

Source

#### pub fn get_short_flag(&self) -> Option<char>

Get the short flag of the subcommand.

Source

#### pub fn get_long_flag(&self) -> Option<&str>

Get the long flag of the subcommand.

Source

#### pub fn get_about(&self) -> Option<&StyledStr>

Get the help message specified via `Command::about`.

Source

#### pub fn get_long_about(&self) -> Option<&StyledStr>

Get the help message specified via `Command::long_about`.

Source

#### pub fn is_flatten_help_set(&self) -> bool

Get the custom section heading specified via `Command::flatten_help`.

Source

#### pub fn get_next_help_heading(&self) -> Option<&str>

Get the custom section heading specified via `Command::next_help_heading`.

Source

#### pub fn get_visible_aliases(&self) -> impl Iterator<Item = &str>

Iterate through the visible aliases for this subcommand.

Source

#### pub fn get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char>

Iterate through the visible short aliases for this subcommand.

Source

#### pub fn get_visible_long_flag_aliases(&self) -> impl Iterator<Item = &str>

Iterate through the visible long aliases for this subcommand.

Source

#### pub fn get_all_aliases(&self) -> impl Iterator<Item = &str>

Iterate through the set of all the aliases for this subcommand, both visible and hidden.

Source

#### pub fn get_all_short_flag_aliases(&self) -> impl Iterator<Item = char>

Iterate through the set of all the short aliases for this subcommand, both visible and hidden.

Source

#### pub fn get_all_long_flag_aliases(&self) -> impl Iterator<Item = &str>

Iterate through the set of all the long aliases for this subcommand, both visible and hidden.

Source

#### pub fn get_aliases(&self) -> impl Iterator<Item = &str>

Iterate through the hidden aliases for this subcommand.

Source

#### pub fn get_color(&self) -> ColorChoice

Should we color the output?

Source

#### pub fn get_styles(&self) -> &Styles

Return the current `Styles` for the `Command`

Source

#### pub fn get_subcommands(&self) -> impl Iterator<Item = &Command>

Iterate through the set of subcommands, getting a reference to each.

Source

#### pub fn get_subcommands_mut(&mut self) -> impl Iterator<Item = &mut Command>

Iterate through the set of subcommands, getting a mutable reference to each.

Source

#### pub fn has_subcommands(&self) -> bool

Returns `true` if this `Command` has subcommands.

Source

#### pub fn get_subcommand_help_heading(&self) -> Option<&str>

Returns the help heading for listing subcommands.

Source

#### pub fn get_subcommand_value_name(&self) -> Option<&str>

Returns the subcommand value name.

Source

#### pub fn get_before_help(&self) -> Option<&StyledStr>

Returns the help heading for listing subcommands.

Source

#### pub fn get_before_long_help(&self) -> Option<&StyledStr>

Returns the help heading for listing subcommands.

Source

#### pub fn get_after_help(&self) -> Option<&StyledStr>

Returns the help heading for listing subcommands.

Source

#### pub fn get_after_long_help(&self) -> Option<&StyledStr>

Returns the help heading for listing subcommands.

Source

#### pub fn find_subcommand(&self, name: impl AsRef<OsStr>) -> Option<&Command>

Find subcommand such that its name or one of aliases equals `name`.

This does not recurse through subcommands of subcommands.

Source

#### pub fn find_subcommand_mut( &mut self, name: impl AsRef<OsStr>, ) -> Option<&mut Command>

Find subcommand such that its name or one of aliases equals `name`, returning a mutable reference to the subcommand.

This does not recurse through subcommands of subcommands.

Source

#### pub fn get_groups(&self) -> impl Iterator<Item = &ArgGroup>

Iterate through the set of groups.

Source

#### pub fn get_arguments(&self) -> impl Iterator<Item = &Arg>

Iterate through the set of arguments.

Source

#### pub fn get_positionals(&self) -> impl Iterator<Item = &Arg>

Iterate through the positionals arguments.

Source

#### pub fn get_opts(&self) -> impl Iterator<Item = &Arg>

Iterate through the options.

Source

#### pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg>

Get a list of all arguments the given argument conflicts with.

If the provided argument is declared as global, the conflicts will be determined based on the propagation rules of global arguments.

###### §Panics

If the given arg contains a conflict with an argument that is unknown to this `Command`.

Source

#### pub fn is_no_binary_name_set(&self) -> bool

Report whether `Command::no_binary_name` is set

Source

#### pub fn is_dont_delimit_trailing_values_set(&self) -> bool

Report whether `Command::dont_delimit_trailing_values` is set

Source

#### pub fn is_disable_version_flag_set(&self) -> bool

Report whether `Command::disable_version_flag` is set

Source

#### pub fn is_propagate_version_set(&self) -> bool

Report whether `Command::propagate_version` is set

Source

#### pub fn is_next_line_help_set(&self) -> bool

Report whether `Command::next_line_help` is set

Source

#### pub fn is_disable_help_flag_set(&self) -> bool

Report whether `Command::disable_help_flag` is set

Source

#### pub fn is_disable_help_subcommand_set(&self) -> bool

Report whether `Command::disable_help_subcommand` is set

Source

#### pub fn is_disable_colored_help_set(&self) -> bool

Report whether `Command::disable_colored_help` is set

Source

#### pub fn is_arg_required_else_help_set(&self) -> bool

Report whether `Command::arg_required_else_help` is set

Source

#### pub fn is_allow_missing_positional_set(&self) -> bool

Report whether `Command::allow_missing_positional` is set

Source

#### pub fn is_hide_set(&self) -> bool

Report whether `Command::hide` is set

Source

#### pub fn is_subcommand_required_set(&self) -> bool

Report whether `Command::subcommand_required` is set

Source

#### pub fn is_allow_external_subcommands_set(&self) -> bool

Report whether `Command::allow_external_subcommands` is set

Source

#### pub fn get_external_subcommand_value_parser(&self) -> Option<&ValueParser>

Configured parser for values passed to an external subcommand

##### §Example

    let cmd = clap::Command::new("raw")
        .external_subcommand_value_parser(clap::value_parser!(String));
    let value_parser = cmd.get_external_subcommand_value_parser();
    println!("{value_parser:?}");

Source

#### pub fn is_args_conflicts_with_subcommands_set(&self) -> bool

Report whether `Command::args_conflicts_with_subcommands` is set

Source

#### pub fn is_subcommand_precedence_over_arg_set(&self) -> bool

Report whether `Command::subcommand_precedence_over_arg` is set

Source

#### pub fn is_subcommand_negates_reqs_set(&self) -> bool

Report whether `Command::subcommand_negates_reqs` is set

Source

#### pub fn is_multicall_set(&self) -> bool

Report whether `Command::multicall` is set

Source

#### pub fn get<T>(&self) -> Option<&T>
where T: CommandExt + Extension,

Available on crate feature `unstable-ext` only.

Access an `CommandExt`

Source

#### pub fn remove<T>(self) -> Option<T>
where T: CommandExt + Extension,

Available on crate feature `unstable-ext` only.

Remove an `CommandExt`

Source§

### impl Command

Source

#### pub fn build(&mut self)

Prepare for introspecting on all included `Command`s

Call this on the top-level `Command` when done building and before reading state for cases like completions, custom help output, etc.

## Trait Implementations§

Source§

### impl Clone for Command

Source§

#### fn clone(&self) -> Command

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

#### fn clone_from(&mut self, source: &Self)

Performs copy-assignment from `source`. Read more
Source§

### impl Debug for Command

Source§

#### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

### impl Default for Command

Source§

#### fn default() -> Command

Returns the “default value” for a type. Read more
Source§

### impl Display for Command

Source§

#### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

### impl From<&Command> for Command

Source§

#### fn from(cmd: &Command) -> Command

Converts to this type from the input type.
Source§

### impl Index<&Id> for Command

Source§

#### type Output = Arg

The returned type after indexing.
Source§

#### fn index(&self, key: &Id) -> &<Command as Index<&Id>>::Output

Performs the indexing (`container[index]`) operation. Read more

## Auto Trait Implementations§

§

### impl !RefUnwindSafe for Command

§

### impl !UnwindSafe for Command

§

### impl Freeze for Command

§

### impl Send for Command

§

### impl Sync for Command

§

### impl Unpin for Command

§

### impl UnsafeUnpin for Command

## Blanket Implementations§

Source§

### impl<T> Any for T
where T: 'static + ?Sized,

Source§

#### fn type_id(&self) -> TypeId

Gets the `TypeId` of `self`. Read more
Source§

### impl<T> Borrow<T> for T
where T: ?Sized,

Source§

#### fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

### impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

#### fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

### impl<T> CloneToUninit for T
where T: Clone,

Source§

#### unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (`clone_to_uninit`)
Performs copy-assignment from `self` to `dest`. Read more
Source§

### impl<T> From<T> for T

Source§

#### fn from(t: T) -> T

Returns the argument unchanged.

Source§

### impl<T, U> Into<U> for T
where U: From<T>,

Source§

#### fn into(self) -> U

Calls `U::from(self)`.

That is, this conversion is whatever the implementation of `From<T> for U` chooses to do.

Source§

### impl<T> ToOwned for T
where T: Clone,

Source§

#### type Owned = T

The resulting type after obtaining ownership.
Source§

#### fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

#### fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

### impl<T> ToString for T
where T: Display + ?Sized,

Source§

#### fn to_string(&self) -> String

Converts the given value to a `String`. Read more
Source§

### impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

#### type Error = Infallible

The type returned in the event of a conversion error.
Source§

#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

### impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

#### type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.