logo

Macro clap::arg

source · []
macro_rules! arg {
    ( $name:ident: $($tail:tt)+ ) => { ... };
    ( $($tail:tt)+ ) => { ... };
}
Expand description

Create an Arg from a usage string.

Allows creation of basic settings for the Arg.

NOTE: Not all settings may be set using the usage string method. Some properties are only available via the builder pattern.

Syntax

Usage strings typically following the form:

[explicit name] [short] [long] [value names] [...] [help string]

Explicit Name

The name may be either a bare-word or a string, followed by a :, like name: or "name":.

Note: This is an optional field, if it’s omitted the argument will use one of the additional fields as the name using the following priority order:

  1. Explicit Name
  2. Long
  3. Value Name

See Arg::id.

Short

A short flag is a - followed by either a bare-character or quoted character, like -f or -'f'.

See Arg::short.

Long

A long flag is a -- followed by either a bare-word or a string, like --foo or --"foo".

NOTE: Dashes in the long name (e.g. --foo-bar) is not supported and quoting is required (e.g. --"foo-bar").

See Arg::long.

Values (Value Notation)

This is set by placing bare-word between:

  • [] like [FOO]
    • Positional argument: optional
    • Named argument: optional value
  • <> like <FOO>: required

See Arg::value_name.

...

... (three consecutive dots/periods) specifies that this argument may occur multiple times (not to be confused with multiple values per occurrence).

See ArgAction::Count and ArgAction::Append.

Help String

The help string is denoted between a pair of double quotes "" and may contain any characters.

Examples

let cmd = Command::new("prog")
    .args(&[
        arg!(--config <FILE> "a required file for the configuration and no short"),
        arg!(-d --debug ... "turns on debugging information and allows multiples"),
        arg!([input] "an optional input file to use")
    ]);

let m = cmd.try_get_matches_from(["prog", "--config", "file.toml"]).unwrap();
assert_eq!(m.get_one::<String>("config").unwrap(), "file.toml");
assert_eq!(*m.get_one::<u8>("debug").unwrap(), 0);
assert_eq!(m.get_one::<String>("input"), None);