logo
pub struct Arg<'help> { /* private fields */ }
Expand description

The abstract representation of a command line argument. Used to set all the options and relationships that define a valid argument for the program.

There are two methods for constructing Args, using the builder pattern and setting options manually, or using a usage string which is far less verbose but has fewer options. You can also use a combination of the two methods to achieve the best of both worlds.

Examples

// Using the traditional builder pattern and setting each option manually
let cfg = Arg::new("config")
      .short('c')
      .long("config")
      .takes_value(true)
      .value_name("FILE")
      .help("Provides a config file to myprog");
// Using a usage string (setting a similar argument to the one above)
let input = arg!(-i --input <FILE> "Provides an input file to the program");

Implementations

Create a new Arg with a unique name.

The name is used to check whether or not the argument was used at runtime, get values, set relationships with other args, etc..

NOTE: In the case of arguments that take values (i.e. Arg::takes_value(true)) and positional arguments (i.e. those without a preceding - or --) the name will also be displayed when the user prints the usage/help information of the program.

Examples
Arg::new("config")
Examples found in repository?
examples/tutorial_builder/03_01_flag_bool.rs (line 6)
3
4
5
6
7
8
9
10
11
12
13
14
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            Arg::new("verbose")
                .short('v')
                .long("verbose")
                .action(ArgAction::SetTrue),
        )
        .get_matches();

    println!("verbose: {:?}", matches.get_flag("verbose"));
}
More examples
Hide additional examples
examples/derive_ref/flatten_hand_args.rs (line 40)
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
    fn augment_args(cmd: Command<'_>) -> Command<'_> {
        cmd.arg(
            Arg::new("foo")
                .short('f')
                .long("foo")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("bar")
                .short('b')
                .long("bar")
                .action(ArgAction::SetTrue),
        )
        .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true))
    }
    fn augment_args_for_update(cmd: Command<'_>) -> Command<'_> {
        cmd.arg(
            Arg::new("foo")
                .short('f')
                .long("foo")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("bar")
                .short('b')
                .long("bar")
                .action(ArgAction::SetTrue),
        )
        .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true))
    }
examples/multicall-busybox.rs (line 22)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
fn main() {
    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
        .multicall(true)
        .subcommand(
            Command::new("busybox")
                .arg_required_else_help(true)
                .subcommand_value_name("APPLET")
                .subcommand_help_heading("APPLETS")
                .arg(
                    Arg::new("install")
                        .long("install")
                        .help("Install hardlinks for all subcommands in path")
                        .exclusive(true)
                        .takes_value(true)
                        .default_missing_value("/usr/local/bin")
                        .value_parser(value_parser!(PathBuf))
                        .use_value_delimiter(false),
                )
                .subcommands(applet_commands()),
        )
        .subcommands(applet_commands());

    let matches = cmd.get_matches();
    let mut subcommand = matches.subcommand();
    if let Some(("busybox", cmd)) = subcommand {
        if cmd.contains_id("install") {
            unimplemented!("Make hardlinks to the executable here");
        }
        subcommand = cmd.subcommand();
    }
    match subcommand {
        Some(("false", _)) => exit(1),
        Some(("true", _)) => exit(0),
        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    }
}
examples/pacman.rs (line 19)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
fn main() {
    let matches = Command::new("pacman")
        .about("package manager utility")
        .version("5.2.1")
        .subcommand_required(true)
        .arg_required_else_help(true)
        .author("Pacman Development Team")
        // Query subcommand
        //
        // Only a few of its arguments are implemented below.
        .subcommand(
            Command::new("query")
                .short_flag('Q')
                .long_flag("query")
                .about("Query the package database.")
                .arg(
                    Arg::new("search")
                        .short('s')
                        .long("search")
                        .help("search locally installed packages for matching strings")
                        .conflicts_with("info")
                        .takes_value(true)
                        .multiple_values(true),
                )
                .arg(
                    Arg::new("info")
                        .long("info")
                        .short('i')
                        .conflicts_with("search")
                        .help("view package information")
                        .takes_value(true)
                        .multiple_values(true),
                ),
        )
        // Sync subcommand
        //
        // Only a few of its arguments are implemented below.
        .subcommand(
            Command::new("sync")
                .short_flag('S')
                .long_flag("sync")
                .about("Synchronize packages.")
                .arg(
                    Arg::new("search")
                        .short('s')
                        .long("search")
                        .conflicts_with("info")
                        .takes_value(true)
                        .multiple_values(true)
                        .help("search remote repositories for matching strings"),
                )
                .arg(
                    Arg::new("info")
                        .long("info")
                        .conflicts_with("search")
                        .short('i')
                        .action(ArgAction::SetTrue)
                        .help("view package information"),
                )
                .arg(
                    Arg::new("package")
                        .help("packages")
                        .required_unless_present("search")
                        .takes_value(true)
                        .multiple_values(true),
                ),
        )
        .get_matches();

    match matches.subcommand() {
        Some(("sync", sync_matches)) => {
            if sync_matches.contains_id("search") {
                let packages: Vec<_> = sync_matches
                    .get_many::<String>("search")
                    .expect("contains_id")
                    .map(|s| s.as_str())
                    .collect();
                let values = packages.join(", ");
                println!("Searching for {}...", values);
                return;
            }

            let packages: Vec<_> = sync_matches
                .get_many::<String>("package")
                .expect("is present")
                .map(|s| s.as_str())
                .collect();
            let values = packages.join(", ");

            if sync_matches.get_flag("info") {
                println!("Retrieving info for {}...", values);
            } else {
                println!("Installing {}...", values);
            }
        }
        Some(("query", query_matches)) => {
            if let Some(packages) = query_matches.get_many::<String>("info") {
                let comma_sep = packages.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
                println!("Retrieving info for {}...", comma_sep);
            } else if let Some(queries) = query_matches.get_many::<String>("search") {
                let comma_sep = queries.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
                println!("Searching Locally for {}...", comma_sep);
            } else {
                println!("Displaying all locally installed packages...");
            }
        }
        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
    }
}

Set the identifier used for referencing this argument in the clap API.

See Arg::new for more details.

Deprecated, replaced with Arg::id to avoid confusion with Arg::value_name

Builder: replaced arg.name(...) with arg.id(...)

Sets the short version of the argument without the preceding -.

By default V and h are used by the auto-generated version and help arguments, respectively. You may use the uppercase V or lowercase h for your own arguments, in which case clap simply will not assign those to the auto-generated version or help arguments.

Examples

When calling short, use a single valid UTF-8 character which will allow using the argument via a single hyphen (-) such as -c:

let m = Command::new("prog")
    .arg(Arg::new("config")
        .short('c')
        .takes_value(true))
    .get_matches_from(vec![
        "prog", "-c", "file.toml"
    ]);

assert_eq!(m.get_one::<String>("config").map(String::as_str), Some("file.toml"));
Examples found in repository?
examples/tutorial_builder/03_01_flag_bool.rs (line 7)
3
4
5
6
7
8
9
10
11
12
13
14
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            Arg::new("verbose")
                .short('v')
                .long("verbose")
                .action(ArgAction::SetTrue),
        )
        .get_matches();

    println!("verbose: {:?}", matches.get_flag("verbose"));
}
More examples
Hide additional examples
examples/derive_ref/flatten_hand_args.rs (line 41)
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
    fn augment_args(cmd: Command<'_>) -> Command<'_> {
        cmd.arg(
            Arg::new("foo")
                .short('f')
                .long("foo")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("bar")
                .short('b')
                .long("bar")
                .action(ArgAction::SetTrue),
        )
        .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true))
    }
    fn augment_args_for_update(cmd: Command<'_>) -> Command<'_> {
        cmd.arg(
            Arg::new("foo")
                .short('f')
                .long("foo")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("bar")
                .short('b')
                .long("bar")
                .action(ArgAction::SetTrue),
        )
        .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true))
    }
examples/pacman.rs (line 20)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
fn main() {
    let matches = Command::new("pacman")
        .about("package manager utility")
        .version("5.2.1")
        .subcommand_required(true)
        .arg_required_else_help(true)
        .author("Pacman Development Team")
        // Query subcommand
        //
        // Only a few of its arguments are implemented below.
        .subcommand(
            Command::new("query")
                .short_flag('Q')
                .long_flag("query")
                .about("Query the package database.")
                .arg(
                    Arg::new("search")
                        .short('s')
                        .long("search")
                        .help("search locally installed packages for matching strings")
                        .conflicts_with("info")
                        .takes_value(true)
                        .multiple_values(true),
                )
                .arg(
                    Arg::new("info")
                        .long("info")
                        .short('i')
                        .conflicts_with("search")
                        .help("view package information")
                        .takes_value(true)
                        .multiple_values(true),
                ),
        )
        // Sync subcommand
        //
        // Only a few of its arguments are implemented below.
        .subcommand(
            Command::new("sync")
                .short_flag('S')
                .long_flag("sync")
                .about("Synchronize packages.")
                .arg(
                    Arg::new("search")
                        .short('s')
                        .long("search")
                        .conflicts_with("info")
                        .takes_value(true)
                        .multiple_values(true)
                        .help("search remote repositories for matching strings"),
                )
                .arg(
                    Arg::new("info")
                        .long("info")
                        .conflicts_with("search")
                        .short('i')
                        .action(ArgAction::SetTrue)
                        .help("view package information"),
                )
                .arg(
                    Arg::new("package")
                        .help("packages")
                        .required_unless_present("search")
                        .takes_value(true)
                        .multiple_values(true),
                ),
        )
        .get_matches();

    match matches.subcommand() {
        Some(("sync", sync_matches)) => {
            if sync_matches.contains_id("search") {
                let packages: Vec<_> = sync_matches
                    .get_many::<String>("search")
                    .expect("contains_id")
                    .map(|s| s.as_str())
                    .collect();
                let values = packages.join(", ");
                println!("Searching for {}...", values);
                return;
            }

            let packages: Vec<_> = sync_matches
                .get_many::<String>("package")
                .expect("is present")
                .map(|s| s.as_str())
                .collect();
            let values = packages.join(", ");

            if sync_matches.get_flag("info") {
                println!("Retrieving info for {}...", values);
            } else {
                println!("Installing {}...", values);
            }
        }
        Some(("query", query_matches)) => {
            if let Some(packages) = query_matches.get_many::<String>("info") {
                let comma_sep = packages.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
                println!("Retrieving info for {}...", comma_sep);
            } else if let Some(queries) = query_matches.get_many::<String>("search") {
                let comma_sep = queries.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
                println!("Searching Locally for {}...", comma_sep);
            } else {
                println!("Displaying all locally installed packages...");
            }
        }
        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
    }
}

Sets the long version of the argument without the preceding --.

By default version and help are used by the auto-generated version and help arguments, respectively. You may use the word version or help for the long form of your own arguments, in which case clap simply will not assign those to the auto-generated version or help arguments.

NOTE: Any leading - characters will be stripped

Examples

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

Setting long allows using the argument via a double hyphen (--) such as --config

let m = Command::new("prog")
    .arg(Arg::new("cfg")
        .long("config")
        .takes_value(true))
    .get_matches_from(vec![
        "prog", "--config", "file.toml"
    ]);

assert_eq!(m.get_one::<String>("cfg").map(String::as_str), Some("file.toml"));
Examples found in repository?
examples/tutorial_builder/03_01_flag_bool.rs (line 8)
3
4
5
6
7
8
9
10
11
12
13
14
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            Arg::new("verbose")
                .short('v')
                .long("verbose")
                .action(ArgAction::SetTrue),
        )
        .get_matches();

    println!("verbose: {:?}", matches.get_flag("verbose"));
}
More examples
Hide additional examples
examples/derive_ref/flatten_hand_args.rs (line 42)
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
    fn augment_args(cmd: Command<'_>) -> Command<'_> {
        cmd.arg(
            Arg::new("foo")
                .short('f')
                .long("foo")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("bar")
                .short('b')
                .long("bar")
                .action(ArgAction::SetTrue),
        )
        .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true))
    }
    fn augment_args_for_update(cmd: Command<'_>) -> Command<'_> {
        cmd.arg(
            Arg::new("foo")
                .short('f')
                .long("foo")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("bar")
                .short('b')
                .long("bar")
                .action(ArgAction::SetTrue),
        )
        .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true))
    }
examples/multicall-busybox.rs (line 23)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
fn main() {
    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
        .multicall(true)
        .subcommand(
            Command::new("busybox")
                .arg_required_else_help(true)
                .subcommand_value_name("APPLET")
                .subcommand_help_heading("APPLETS")
                .arg(
                    Arg::new("install")
                        .long("install")
                        .help("Install hardlinks for all subcommands in path")
                        .exclusive(true)
                        .takes_value(true)
                        .default_missing_value("/usr/local/bin")
                        .value_parser(value_parser!(PathBuf))
                        .use_value_delimiter(false),
                )
                .subcommands(applet_commands()),
        )
        .subcommands(applet_commands());

    let matches = cmd.get_matches();
    let mut subcommand = matches.subcommand();
    if let Some(("busybox", cmd)) = subcommand {
        if cmd.contains_id("install") {
            unimplemented!("Make hardlinks to the executable here");
        }
        subcommand = cmd.subcommand();
    }
    match subcommand {
        Some(("false", _)) => exit(1),
        Some(("true", _)) => exit(0),
        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    }
}
examples/pacman.rs (line 21)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
fn main() {
    let matches = Command::new("pacman")
        .about("package manager utility")
        .version("5.2.1")
        .subcommand_required(true)
        .arg_required_else_help(true)
        .author("Pacman Development Team")
        // Query subcommand
        //
        // Only a few of its arguments are implemented below.
        .subcommand(
            Command::new("query")
                .short_flag('Q')
                .long_flag("query")
                .about("Query the package database.")
                .arg(
                    Arg::new("search")
                        .short('s')
                        .long("search")
                        .help("search locally installed packages for matching strings")
                        .conflicts_with("info")
                        .takes_value(true)
                        .multiple_values(true),
                )
                .arg(
                    Arg::new("info")
                        .long("info")
                        .short('i')
                        .conflicts_with("search")
                        .help("view package information")
                        .takes_value(true)
                        .multiple_values(true),
                ),
        )
        // Sync subcommand
        //
        // Only a few of its arguments are implemented below.
        .subcommand(
            Command::new("sync")
                .short_flag('S')
                .long_flag("sync")
                .about("Synchronize packages.")
                .arg(
                    Arg::new("search")
                        .short('s')
                        .long("search")
                        .conflicts_with("info")
                        .takes_value(true)
                        .multiple_values(true)
                        .help("search remote repositories for matching strings"),
                )
                .arg(
                    Arg::new("info")
                        .long("info")
                        .conflicts_with("search")
                        .short('i')
                        .action(ArgAction::SetTrue)
                        .help("view package information"),
                )
                .arg(
                    Arg::new("package")
                        .help("packages")
                        .required_unless_present("search")
                        .takes_value(true)
                        .multiple_values(true),
                ),
        )
        .get_matches();

    match matches.subcommand() {
        Some(("sync", sync_matches)) => {
            if sync_matches.contains_id("search") {
                let packages: Vec<_> = sync_matches
                    .get_many::<String>("search")
                    .expect("contains_id")
                    .map(|s| s.as_str())
                    .collect();
                let values = packages.join(", ");
                println!("Searching for {}...", values);
                return;
            }

            let packages: Vec<_> = sync_matches
                .get_many::<String>("package")
                .expect("is present")
                .map(|s| s.as_str())
                .collect();
            let values = packages.join(", ");

            if sync_matches.get_flag("info") {
                println!("Retrieving info for {}...", values);
            } else {
                println!("Installing {}...", values);
            }
        }
        Some(("query", query_matches)) => {
            if let Some(packages) = query_matches.get_many::<String>("info") {
                let comma_sep = packages.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
                println!("Retrieving info for {}...", comma_sep);
            } else if let Some(queries) = query_matches.get_many::<String>("search") {
                let comma_sep = queries.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
                println!("Searching Locally for {}...", comma_sep);
            } else {
                println!("Displaying all locally installed packages...");
            }
        }
        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
    }
}

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

This is more efficient, and easier than creating multiple hidden arguments as one only needs to check for the existence of this command, and not all variants.

Examples
let m = Command::new("prog")
            .arg(Arg::new("test")
            .long("test")
            .alias("alias")
            .takes_value(true))
       .get_matches_from(vec![
            "prog", "--alias", "cool"
        ]);
assert!(m.contains_id("test"));
assert_eq!(m.value_of("test"), Some("cool"));

Add an alias, which functions as a hidden short flag.

This is more efficient, and easier than creating multiple hidden arguments as one only needs to check for the existence of this command, and not all variants.

Examples
let m = Command::new("prog")
            .arg(Arg::new("test")
            .short('t')
            .short_alias('e')
            .takes_value(true))
       .get_matches_from(vec![
            "prog", "-e", "cool"
        ]);
assert!(m.contains_id("test"));
assert_eq!(m.value_of("test"), Some("cool"));

Add aliases, which function as hidden long flags.

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("prog")
            .arg(Arg::new("test")
                    .long("test")
                    .aliases(&["do-stuff", "do-tests", "tests"])
                    .action(ArgAction::SetTrue)
                    .help("the file to add")
                    .required(false))
            .get_matches_from(vec![
                "prog", "--do-tests"
            ]);
assert_eq!(*m.get_one::<bool>("test").expect("defaulted by clap"), true);

Add aliases, which functions as a hidden short flag.

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("prog")
            .arg(Arg::new("test")
                    .short('t')
                    .short_aliases(&['e', 's'])
                    .action(ArgAction::SetTrue)
                    .help("the file to add")
                    .required(false))
            .get_matches_from(vec![
                "prog", "-s"
            ]);
assert_eq!(*m.get_one::<bool>("test").expect("defaulted by clap"), true);

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

Like Arg::alias, except that they are visible inside the help message.

Examples
let m = Command::new("prog")
            .arg(Arg::new("test")
                .visible_alias("something-awesome")
                .long("test")
                .takes_value(true))
       .get_matches_from(vec![
            "prog", "--something-awesome", "coffee"
        ]);
assert!(m.contains_id("test"));
assert_eq!(m.value_of("test"), Some("coffee"));

Add an alias, which functions as a visible short flag.

Like Arg::short_alias, except that they are visible inside the help message.

Examples
let m = Command::new("prog")
            .arg(Arg::new("test")
                .long("test")
                .visible_short_alias('t')
                .takes_value(true))
       .get_matches_from(vec![
            "prog", "-t", "coffee"
        ]);
assert!(m.contains_id("test"));
assert_eq!(m.value_of("test"), Some("coffee"));

Add aliases, which function as visible long flags.

Like Arg::aliases, except that they are visible inside the help message.

Examples
let m = Command::new("prog")
            .arg(Arg::new("test")
                .long("test")
                .action(ArgAction::SetTrue)
                .visible_aliases(&["something", "awesome", "cool"]))
       .get_matches_from(vec![
            "prog", "--awesome"
        ]);
assert_eq!(*m.get_one::<bool>("test").expect("defaulted by clap"), true);

Add aliases, which function as visible short flags.

Like Arg::short_aliases, except that they are visible inside the help message.

Examples
let m = Command::new("prog")
            .arg(Arg::new("test")
                .long("test")
                .action(ArgAction::SetTrue)
                .visible_short_aliases(&['t', 'e']))
       .get_matches_from(vec![
            "prog", "-t"
        ]);
assert_eq!(*m.get_one::<bool>("test").expect("defaulted by clap"), true);

Specifies the index of a positional argument starting at 1.

NOTE: The index refers to position according to other positional argument. It does not define position in the argument list as a whole.

NOTE: You can optionally leave off the index method, and the index will be assigned in order of evaluation. Utilizing the index method allows for setting indexes out of order

NOTE: This is only meant to be used for positional arguments and shouldn’t to be used with Arg::short or Arg::long.

NOTE: When utilized with Arg::multiple_values(true), only the last positional argument may be defined as multiple (i.e. with the highest index)

Panics

Command will panic! if indexes are skipped (such as defining index(1) and index(3) but not index(2), or a positional argument is defined as multiple and is not the highest index

Examples
Arg::new("config")
    .index(1)
let m = Command::new("prog")
    .arg(Arg::new("mode")
        .index(1))
    .arg(Arg::new("debug")
        .long("debug"))
    .get_matches_from(vec![
        "prog", "--debug", "fast"
    ]);

assert!(m.contains_id("mode"));
assert_eq!(m.value_of("mode"), Some("fast")); // notice index(1) means "first positional"
                                              // *not* first argument

This arg is the last, or final, positional argument (i.e. has the highest index) and is only able to be accessed via the -- syntax (i.e. $ prog args -- last_arg).

Even, if no other arguments are left to parse, if the user omits the -- syntax they will receive an UnknownArgument error. Setting an argument to .last(true) also allows one to access this arg early using the -- syntax. Accessing an arg early, even with the -- syntax is otherwise not possible.

NOTE: This will change the usage string to look like $ prog [OPTIONS] [-- <ARG>] if ARG is marked as .last(true).

NOTE: This setting will imply crate::Command::dont_collapse_args_in_usage because failing to set this can make the usage string very confusing.

NOTE: This setting only applies to positional arguments, and has no effect on OPTIONS

NOTE: Setting this requires Arg::takes_value

CAUTION: Using this setting and having child subcommands is not recommended with the exception of also using crate::Command::args_conflicts_with_subcommands (or crate::Command::subcommand_negates_reqs if the argument marked Last is also marked Arg::required)

Examples
Arg::new("args")
    .takes_value(true)
    .last(true)

Setting last ensures the arg has the highest index of all positional args and requires that the -- syntax be used to access it early.

let res = Command::new("prog")
    .arg(Arg::new("first"))
    .arg(Arg::new("second"))
    .arg(Arg::new("third")
        .takes_value(true)
        .last(true))
    .try_get_matches_from(vec![
        "prog", "one", "--", "three"
    ]);

assert!(res.is_ok());
let m = res.unwrap();
assert_eq!(m.value_of("third"), Some("three"));
assert!(m.value_of("second").is_none());

Even if the positional argument marked Last is the only argument left to parse, failing to use the -- syntax results in an error.

let res = Command::new("prog")
    .arg(Arg::new("first"))
    .arg(Arg::new("second"))
    .arg(Arg::new("third")
        .takes_value(true)
        .last(true))
    .try_get_matches_from(vec![
        "prog", "one", "two", "three"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
Examples found in repository?
examples/escaped-positional.rs (line 15)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(arg!(eff: -f).action(ArgAction::SetTrue))
        .arg(
            arg!(pea: -p <PEAR>)
                .required(false)
                .value_parser(value_parser!(String)),
        )
        .arg(
            // Indicates that `slop` is only accessible after `--`.
            arg!(slop: [SLOP])
                .multiple_values(true)
                .last(true)
                .value_parser(value_parser!(String)),
        )
        .get_matches();

    // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`...

    // -f used: true
    println!("-f used: {:?}", matches.get_flag("eff"));
    // -p's value: Some("bob")
    println!("-p's value: {:?}", matches.get_one::<String>("pea"));
    // 'slops' values: Some(["sloppy", "slop", "slop"])
    println!(
        "'slops' values: {:?}",
        matches
            .get_many::<String>("slop")
            .map(|vals| vals.collect::<Vec<_>>())
            .unwrap_or_default()
    );

    // Continued program logic goes here...
}

Specifies that the argument must be present.

Required by default means it is required, when no other conflicting rules or overrides have been evaluated. Conflicting rules take precedence over being required.

Pro tip: Flags (i.e. not positional, or arguments that take values) shouldn’t be required by default. This is because if a flag were to be required, it should simply be implied. No additional information is required from user. Flags by their very nature are simply boolean on/off switches. The only time a user should be required to use a flag is if the operation is destructive in nature, and the user is essentially proving to you, “Yes, I know what I’m doing.”

Examples
Arg::new("config")
    .required(true)

Setting required requires that the argument be used at runtime.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .required(true)
        .takes_value(true)
        .long("config"))
    .try_get_matches_from(vec![
        "prog", "--config", "file.conf",
    ]);

assert!(res.is_ok());

Setting required and then not supplying that argument at runtime is an error.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .required(true)
        .takes_value(true)
        .long("config"))
    .try_get_matches_from(vec![
        "prog"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
Examples found in repository?
examples/git.rs (line 42)
41
42
43
fn push_args() -> Vec<clap::Arg<'static>> {
    vec![arg!(-m --message <MESSAGE>).required(false)]
}
More examples
Hide additional examples
examples/tutorial_builder/03_02_option.rs (line 5)
3
4
5
6
7
8
9
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(arg!(-n --name <NAME>).required(false))
        .get_matches();

    println!("name: {:?}", matches.get_one::<String>("name"));
}
examples/cargo-example.rs (line 8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fn main() {
    let cmd = clap::Command::new("cargo")
        .bin_name("cargo")
        .subcommand_required(true)
        .subcommand(
            clap::command!("example").arg(
                clap::arg!(--"manifest-path" <PATH>)
                    .required(false)
                    .value_parser(clap::value_parser!(std::path::PathBuf)),
            ),
        );
    let matches = cmd.get_matches();
    let matches = match matches.subcommand() {
        Some(("example", matches)) => matches,
        _ => unreachable!("clap should ensure we don't get here"),
    };
    let manifest_path = matches.get_one::<std::path::PathBuf>("manifest-path");
    println!("{:?}", manifest_path);
}
examples/escaped-positional.rs (line 8)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(arg!(eff: -f).action(ArgAction::SetTrue))
        .arg(
            arg!(pea: -p <PEAR>)
                .required(false)
                .value_parser(value_parser!(String)),
        )
        .arg(
            // Indicates that `slop` is only accessible after `--`.
            arg!(slop: [SLOP])
                .multiple_values(true)
                .last(true)
                .value_parser(value_parser!(String)),
        )
        .get_matches();

    // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`...

    // -f used: true
    println!("-f used: {:?}", matches.get_flag("eff"));
    // -p's value: Some("bob")
    println!("-p's value: {:?}", matches.get_one::<String>("pea"));
    // 'slops' values: Some(["sloppy", "slop", "slop"])
    println!(
        "'slops' values: {:?}",
        matches
            .get_many::<String>("slop")
            .map(|vals| vals.collect::<Vec<_>>())
            .unwrap_or_default()
    );

    // Continued program logic goes here...
}
examples/tutorial_builder/01_quick.rs (line 13)
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(arg!([name] "Optional name to operate on"))
        .arg(
            arg!(
                -c --config <FILE> "Sets a custom config file"
            )
            // We don't have syntax yet for optional options, so manually calling `required`
            .required(false)
            .value_parser(value_parser!(PathBuf)),
        )
        .arg(
            arg!(
                -d --debug "Turn debugging information on"
            )
            .action(ArgAction::Count),
        )
        .subcommand(
            Command::new("test")
                .about("does testing things")
                .arg(arg!(-l --list "lists test values").action(ArgAction::SetTrue)),
        )
        .get_matches();

    // You can check the value provided by positional arguments, or option arguments
    if let Some(name) = matches.get_one::<String>("name") {
        println!("Value for name: {}", name);
    }

    if let Some(config_path) = matches.get_one::<PathBuf>("config") {
        println!("Value for config: {}", config_path.display());
    }

    // You can see how many times a particular flag or argument occurred
    // Note, only flags can have multiple occurrences
    match matches
        .get_one::<u8>("debug")
        .expect("Count's are defaulted")
    {
        0 => println!("Debug mode is off"),
        1 => println!("Debug mode is kind of on"),
        2 => println!("Debug mode is on"),
        _ => println!("Don't be crazy"),
    }

    // You can check for the existence of subcommands, and if found use their
    // matches just as you would the top level cmd
    if let Some(matches) = matches.subcommand_matches("test") {
        // "$ myapp test" was run
        if *matches.get_one::<bool>("list").expect("defaulted by clap") {
            // "$ myapp test -l" was run
            println!("Printing testing lists...");
        } else {
            println!("Not printing testing lists...");
        }
    }

    // Continued program logic goes here...
}
examples/tutorial_builder/04_03_relations.rs (line 9)
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
fn main() {
    // Create application like normal
    let matches = command!() // requires `cargo` feature
        // Add the version arguments
        .arg(arg!(--"set-ver" <VER> "set version manually").required(false))
        .arg(arg!(--major         "auto inc major").action(ArgAction::SetTrue))
        .arg(arg!(--minor         "auto inc minor").action(ArgAction::SetTrue))
        .arg(arg!(--patch         "auto inc patch").action(ArgAction::SetTrue))
        // Create a group, make it required, and add the above arguments
        .group(
            ArgGroup::new("vers")
                .required(true)
                .args(&["set-ver", "major", "minor", "patch"]),
        )
        // Arguments can also be added to a group individually, these two arguments
        // are part of the "input" group which is not required
        .arg(
            arg!([INPUT_FILE] "some regular input")
                .value_parser(value_parser!(PathBuf))
                .group("input"),
        )
        .arg(
            arg!(--"spec-in" <SPEC_IN> "some special input argument")
                .required(false)
                .value_parser(value_parser!(PathBuf))
                .group("input"),
        )
        // Now let's assume we have a -c [config] argument which requires one of
        // (but **not** both) the "input" arguments
        .arg(
            arg!(config: -c <CONFIG>)
                .required(false)
                .value_parser(value_parser!(PathBuf))
                .requires("input"),
        )
        .get_matches();

    // Let's assume the old version 1.2.3
    let mut major = 1;
    let mut minor = 2;
    let mut patch = 3;

    // See if --set-ver was used to set the version manually
    let version = if let Some(ver) = matches.get_one::<String>("set-ver") {
        ver.to_owned()
    } else {
        // Increment the one requested (in a real program, we'd reset the lower numbers)
        let (maj, min, pat) = (
            matches.get_flag("major"),
            matches.get_flag("minor"),
            matches.get_flag("patch"),
        );
        match (maj, min, pat) {
            (true, _, _) => major += 1,
            (_, true, _) => minor += 1,
            (_, _, true) => patch += 1,
            _ => unreachable!(),
        };
        format!("{}.{}.{}", major, minor, patch)
    };

    println!("Version: {}", version);

    // Check for usage of -c
    if matches.contains_id("config") {
        let input = matches
            .get_one::<PathBuf>("INPUT_FILE")
            .unwrap_or_else(|| matches.get_one::<PathBuf>("spec-in").unwrap())
            .display();
        println!(
            "Doing work using input {} and config {}",
            input,
            matches.get_one::<PathBuf>("config").unwrap().display()
        );
    }
}

Sets an argument that is required when this one is present

i.e. when using this argument, the following argument must be present.

NOTE: Conflicting rules and override rules take precedence over being required

Examples
Arg::new("config")
    .requires("input")

Setting Arg::requires(name) requires that the argument be used at runtime if the defining argument is used. If the defining argument isn’t used, the other argument isn’t required

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .takes_value(true)
        .requires("input")
        .long("config"))
    .arg(Arg::new("input"))
    .try_get_matches_from(vec![
        "prog"
    ]);

assert!(res.is_ok()); // We didn't use cfg, so input wasn't required

Setting Arg::requires(name) and not supplying that argument is an error.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .takes_value(true)
        .requires("input")
        .long("config"))
    .arg(Arg::new("input"))
    .try_get_matches_from(vec![
        "prog", "--config", "file.conf"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
Examples found in repository?
examples/tutorial_builder/04_03_relations.rs (line 38)
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
fn main() {
    // Create application like normal
    let matches = command!() // requires `cargo` feature
        // Add the version arguments
        .arg(arg!(--"set-ver" <VER> "set version manually").required(false))
        .arg(arg!(--major         "auto inc major").action(ArgAction::SetTrue))
        .arg(arg!(--minor         "auto inc minor").action(ArgAction::SetTrue))
        .arg(arg!(--patch         "auto inc patch").action(ArgAction::SetTrue))
        // Create a group, make it required, and add the above arguments
        .group(
            ArgGroup::new("vers")
                .required(true)
                .args(&["set-ver", "major", "minor", "patch"]),
        )
        // Arguments can also be added to a group individually, these two arguments
        // are part of the "input" group which is not required
        .arg(
            arg!([INPUT_FILE] "some regular input")
                .value_parser(value_parser!(PathBuf))
                .group("input"),
        )
        .arg(
            arg!(--"spec-in" <SPEC_IN> "some special input argument")
                .required(false)
                .value_parser(value_parser!(PathBuf))
                .group("input"),
        )
        // Now let's assume we have a -c [config] argument which requires one of
        // (but **not** both) the "input" arguments
        .arg(
            arg!(config: -c <CONFIG>)
                .required(false)
                .value_parser(value_parser!(PathBuf))
                .requires("input"),
        )
        .get_matches();

    // Let's assume the old version 1.2.3
    let mut major = 1;
    let mut minor = 2;
    let mut patch = 3;

    // See if --set-ver was used to set the version manually
    let version = if let Some(ver) = matches.get_one::<String>("set-ver") {
        ver.to_owned()
    } else {
        // Increment the one requested (in a real program, we'd reset the lower numbers)
        let (maj, min, pat) = (
            matches.get_flag("major"),
            matches.get_flag("minor"),
            matches.get_flag("patch"),
        );
        match (maj, min, pat) {
            (true, _, _) => major += 1,
            (_, true, _) => minor += 1,
            (_, _, true) => patch += 1,
            _ => unreachable!(),
        };
        format!("{}.{}.{}", major, minor, patch)
    };

    println!("Version: {}", version);

    // Check for usage of -c
    if matches.contains_id("config") {
        let input = matches
            .get_one::<PathBuf>("INPUT_FILE")
            .unwrap_or_else(|| matches.get_one::<PathBuf>("spec-in").unwrap())
            .display();
        println!(
            "Doing work using input {} and config {}",
            input,
            matches.get_one::<PathBuf>("config").unwrap().display()
        );
    }
}

This argument must be passed alone; it conflicts with all other arguments.

Examples
Arg::new("config")
    .exclusive(true)

Setting an exclusive argument and having any other arguments present at runtime is an error.

let res = Command::new("prog")
    .arg(Arg::new("exclusive")
        .takes_value(true)
        .exclusive(true)
        .long("exclusive"))
    .arg(Arg::new("debug")
        .long("debug"))
    .arg(Arg::new("input"))
    .try_get_matches_from(vec![
        "prog", "--exclusive", "file.conf", "file.txt"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
Examples found in repository?
examples/multicall-busybox.rs (line 25)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
fn main() {
    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
        .multicall(true)
        .subcommand(
            Command::new("busybox")
                .arg_required_else_help(true)
                .subcommand_value_name("APPLET")
                .subcommand_help_heading("APPLETS")
                .arg(
                    Arg::new("install")
                        .long("install")
                        .help("Install hardlinks for all subcommands in path")
                        .exclusive(true)
                        .takes_value(true)
                        .default_missing_value("/usr/local/bin")
                        .value_parser(value_parser!(PathBuf))
                        .use_value_delimiter(false),
                )
                .subcommands(applet_commands()),
        )
        .subcommands(applet_commands());

    let matches = cmd.get_matches();
    let mut subcommand = matches.subcommand();
    if let Some(("busybox", cmd)) = subcommand {
        if cmd.contains_id("install") {
            unimplemented!("Make hardlinks to the executable here");
        }
        subcommand = cmd.subcommand();
    }
    match subcommand {
        Some(("false", _)) => exit(1),
        Some(("true", _)) => exit(0),
        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    }
}

Specifies that an argument can be matched to all child Subcommands.

NOTE: Global arguments only propagate down, not up (to parent commands), however their values once a user uses them will be propagated back up to parents. In effect, this means one should define all global arguments at the top level, however it doesn’t matter where the user uses the global argument.

Examples

Assume an application with two subcommands, and you’d like to define a --verbose flag that can be called on any of the subcommands and parent, but you don’t want to clutter the source with three duplicate Arg definitions.

let m = Command::new("prog")
    .arg(Arg::new("verb")
        .long("verbose")
        .short('v')
        .action(ArgAction::SetTrue)
        .global(true))
    .subcommand(Command::new("test"))
    .subcommand(Command::new("do-stuff"))
    .get_matches_from(vec![
        "prog", "do-stuff", "--verbose"
    ]);

assert_eq!(m.subcommand_name(), Some("do-stuff"));
let sub_m = m.subcommand_matches("do-stuff").unwrap();
assert_eq!(*sub_m.get_one::<bool>("verb").expect("defaulted by clap"), true);

Deprecated, replaced with Arg::action (Issue #3772)

Deprecated, for flags, this is replaced with RangedI64ValueParser::range

Derive: #[clap(action = ArgAction::Count, value_parser = value_parser!(u8).range(..max))]

Builder: arg.action(ArgAction::Count).value_parser(value_parser!(u8).range(..max))

Check if the ArgSettings variant is currently set on the argument.

Apply a setting to the argument.

See ArgSettings for a full list of possibilities and examples.

Examples
Arg::new("config")
    .setting(ArgSettings::Required)
    .setting(ArgSettings::TakesValue)
Arg::new("config")
    .setting(ArgSettings::Required | ArgSettings::TakesValue)

Remove a setting from the argument.

See ArgSettings for a full list of possibilities and examples.

Examples
Arg::new("config")
    .unset_setting(ArgSettings::Required)
    .unset_setting(ArgSettings::TakesValue)
Arg::new("config")
    .unset_setting(ArgSettings::Required | ArgSettings::TakesValue)

Specifies that the argument takes a value at run time.

NOTE: values for arguments may be specified in any of the following methods

  • Using a space such as -o value or --option value
  • Using an equals and no space such as -o=value or --option=value
  • Use a short and no space such as -ovalue

NOTE: By default, args which allow multiple values are delimited by commas, meaning --option=val1,val2,val3 is three values for the --option argument. If you wish to change the delimiter to another character you can use Arg::value_delimiter(char), alternatively you can turn delimiting values OFF by using Arg::use_value_delimiter(false)

Examples
let m = Command::new("prog")
    .arg(Arg::new("mode")
        .long("mode")
        .takes_value(true))
    .get_matches_from(vec![
        "prog", "--mode", "fast"
    ]);

assert!(m.contains_id("mode"));
assert_eq!(m.value_of("mode"), Some("fast"));
Examples found in repository?
examples/derive_ref/flatten_hand_args.rs (line 51)
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
    fn augment_args(cmd: Command<'_>) -> Command<'_> {
        cmd.arg(
            Arg::new("foo")
                .short('f')
                .long("foo")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("bar")
                .short('b')
                .long("bar")
                .action(ArgAction::SetTrue),
        )
        .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true))
    }
    fn augment_args_for_update(cmd: Command<'_>) -> Command<'_> {
        cmd.arg(
            Arg::new("foo")
                .short('f')
                .long("foo")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("bar")
                .short('b')
                .long("bar")
                .action(ArgAction::SetTrue),
        )
        .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true))
    }
More examples
Hide additional examples
examples/multicall-busybox.rs (line 26)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
fn main() {
    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
        .multicall(true)
        .subcommand(
            Command::new("busybox")
                .arg_required_else_help(true)
                .subcommand_value_name("APPLET")
                .subcommand_help_heading("APPLETS")
                .arg(
                    Arg::new("install")
                        .long("install")
                        .help("Install hardlinks for all subcommands in path")
                        .exclusive(true)
                        .takes_value(true)
                        .default_missing_value("/usr/local/bin")
                        .value_parser(value_parser!(PathBuf))
                        .use_value_delimiter(false),
                )
                .subcommands(applet_commands()),
        )
        .subcommands(applet_commands());

    let matches = cmd.get_matches();
    let mut subcommand = matches.subcommand();
    if let Some(("busybox", cmd)) = subcommand {
        if cmd.contains_id("install") {
            unimplemented!("Make hardlinks to the executable here");
        }
        subcommand = cmd.subcommand();
    }
    match subcommand {
        Some(("false", _)) => exit(1),
        Some(("true", _)) => exit(0),
        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    }
}
examples/pacman.rs (line 24)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
fn main() {
    let matches = Command::new("pacman")
        .about("package manager utility")
        .version("5.2.1")
        .subcommand_required(true)
        .arg_required_else_help(true)
        .author("Pacman Development Team")
        // Query subcommand
        //
        // Only a few of its arguments are implemented below.
        .subcommand(
            Command::new("query")
                .short_flag('Q')
                .long_flag("query")
                .about("Query the package database.")
                .arg(
                    Arg::new("search")
                        .short('s')
                        .long("search")
                        .help("search locally installed packages for matching strings")
                        .conflicts_with("info")
                        .takes_value(true)
                        .multiple_values(true),
                )
                .arg(
                    Arg::new("info")
                        .long("info")
                        .short('i')
                        .conflicts_with("search")
                        .help("view package information")
                        .takes_value(true)
                        .multiple_values(true),
                ),
        )
        // Sync subcommand
        //
        // Only a few of its arguments are implemented below.
        .subcommand(
            Command::new("sync")
                .short_flag('S')
                .long_flag("sync")
                .about("Synchronize packages.")
                .arg(
                    Arg::new("search")
                        .short('s')
                        .long("search")
                        .conflicts_with("info")
                        .takes_value(true)
                        .multiple_values(true)
                        .help("search remote repositories for matching strings"),
                )
                .arg(
                    Arg::new("info")
                        .long("info")
                        .conflicts_with("search")
                        .short('i')
                        .action(ArgAction::SetTrue)
                        .help("view package information"),
                )
                .arg(
                    Arg::new("package")
                        .help("packages")
                        .required_unless_present("search")
                        .takes_value(true)
                        .multiple_values(true),
                ),
        )
        .get_matches();

    match matches.subcommand() {
        Some(("sync", sync_matches)) => {
            if sync_matches.contains_id("search") {
                let packages: Vec<_> = sync_matches
                    .get_many::<String>("search")
                    .expect("contains_id")
                    .map(|s| s.as_str())
                    .collect();
                let values = packages.join(", ");
                println!("Searching for {}...", values);
                return;
            }

            let packages: Vec<_> = sync_matches
                .get_many::<String>("package")
                .expect("is present")
                .map(|s| s.as_str())
                .collect();
            let values = packages.join(", ");

            if sync_matches.get_flag("info") {
                println!("Retrieving info for {}...", values);
            } else {
                println!("Installing {}...", values);
            }
        }
        Some(("query", query_matches)) => {
            if let Some(packages) = query_matches.get_many::<String>("info") {
                let comma_sep = packages.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
                println!("Retrieving info for {}...", comma_sep);
            } else if let Some(queries) = query_matches.get_many::<String>("search") {
                let comma_sep = queries.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
                println!("Searching Locally for {}...", comma_sep);
            } else {
                println!("Displaying all locally installed packages...");
            }
        }
        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
    }
}

Specify the behavior when parsing an argument

Examples
let cmd = Command::new("mycmd")
    .arg(
        Arg::new("flag")
            .long("flag")
            .action(clap::ArgAction::Set)
    );

let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap();
assert!(matches.contains_id("flag"));
assert_eq!(matches.occurrences_of("flag"), 0);
assert_eq!(
    matches.get_many::<String>("flag").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(),
    vec!["value"]
);
Examples found in repository?
examples/tutorial_builder/03_01_flag_count.rs (line 5)
3
4
5
6
7
8
9
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(arg!(-v - -verbose).action(ArgAction::Count))
        .get_matches();

    println!("verbose: {:?}", matches.get_count("verbose"));
}
More examples
Hide additional examples
examples/tutorial_builder/03_01_flag_bool.rs (line 9)
3
4
5
6
7
8
9
10
11
12
13
14
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            Arg::new("verbose")
                .short('v')
                .long("verbose")
                .action(ArgAction::SetTrue),
        )
        .get_matches();

    println!("verbose: {:?}", matches.get_flag("verbose"));
}
examples/derive_ref/flatten_hand_args.rs (line 43)
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
    fn augment_args(cmd: Command<'_>) -> Command<'_> {
        cmd.arg(
            Arg::new("foo")
                .short('f')
                .long("foo")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("bar")
                .short('b')
                .long("bar")
                .action(ArgAction::SetTrue),
        )
        .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true))
    }
    fn augment_args_for_update(cmd: Command<'_>) -> Command<'_> {
        cmd.arg(
            Arg::new("foo")
                .short('f')
                .long("foo")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("bar")
                .short('b')
                .long("bar")
                .action(ArgAction::SetTrue),
        )
        .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true))
    }
examples/tutorial_builder/02_app_settings.rs (line 7)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fn main() {
    let matches = command!() // requires `cargo` feature
        .global_setting(AppSettings::DeriveDisplayOrder)
        .allow_negative_numbers(true)
        .arg(arg!(--two <VALUE>).action(ArgAction::Set))
        .arg(arg!(--one <VALUE>).action(ArgAction::Set))
        .get_matches();

    println!(
        "two: {:?}",
        matches.get_one::<String>("two").expect("required")
    );
    println!(
        "one: {:?}",
        matches.get_one::<String>("one").expect("required")
    );
}
examples/derive_ref/augment_args.rs (line 10)
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
fn main() {
    let cli = Command::new("CLI").arg(arg!(-b - -built).action(clap::ArgAction::SetTrue));
    // Augment built args with derived args
    let cli = DerivedArgs::augment_args(cli);

    let matches = cli.get_matches();
    println!("Value of built: {:?}", matches.get_flag("built"));
    println!(
        "Value of derived via ArgMatches: {:?}",
        matches.get_flag("derived")
    );

    // Since DerivedArgs implements FromArgMatches, we can extract it from the unstructured ArgMatches.
    // This is the main benefit of using derived arguments.
    let derived_matches = DerivedArgs::from_arg_matches(&matches)
        .map_err(|err| err.exit())
        .unwrap();
    println!("Value of derived: {:#?}", derived_matches);
}
examples/escaped-positional.rs (line 5)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(arg!(eff: -f).action(ArgAction::SetTrue))
        .arg(
            arg!(pea: -p <PEAR>)
                .required(false)
                .value_parser(value_parser!(String)),
        )
        .arg(
            // Indicates that `slop` is only accessible after `--`.
            arg!(slop: [SLOP])
                .multiple_values(true)
                .last(true)
                .value_parser(value_parser!(String)),
        )
        .get_matches();

    // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`...

    // -f used: true
    println!("-f used: {:?}", matches.get_flag("eff"));
    // -p's value: Some("bob")
    println!("-p's value: {:?}", matches.get_one::<String>("pea"));
    // 'slops' values: Some(["sloppy", "slop", "slop"])
    println!(
        "'slops' values: {:?}",
        matches
            .get_many::<String>("slop")
            .map(|vals| vals.collect::<Vec<_>>())
            .unwrap_or_default()
    );

    // Continued program logic goes here...
}

Specify the type of the argument.

This allows parsing and validating a value before storing it into ArgMatches.

See also

let mut cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("color")
            .long("color")
            .value_parser(["always", "auto", "never"])
            .default_value("auto")
    )
    .arg(
        clap::Arg::new("hostname")
            .long("hostname")
            .value_parser(clap::builder::NonEmptyStringValueParser::new())
            .takes_value(true)
            .required(true)
    )
    .arg(
        clap::Arg::new("port")
            .long("port")
            .value_parser(clap::value_parser!(u16).range(3000..))
            .takes_value(true)
            .required(true)
    );

let m = cmd.try_get_matches_from_mut(
    ["cmd", "--hostname", "rust-lang.org", "--port", "3001"]
).unwrap();

let color: &String = m.get_one("color")
    .expect("default");
assert_eq!(color, "auto");

let hostname: &String = m.get_one("hostname")
    .expect("required");
assert_eq!(hostname, "rust-lang.org");

let port: u16 = *m.get_one("port")
    .expect("required");
assert_eq!(port, 3001);
Examples found in repository?
examples/tutorial_builder/05_01_assert.rs (line 18)
13
14
15
16
17
18
19
20
fn cmd() -> clap::Command<'static> {
    command!() // requires `cargo` feature
        .arg(
            arg!(<PORT>)
                .help("Network port to use")
                .value_parser(value_parser!(usize)),
        )
}
More examples
Hide additional examples
examples/tutorial_builder/04_02_validate.rs (line 10)
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            arg!(<PORT>)
                .help("Network port to use")
                .value_parser(port_in_range),
        )
        .get_matches();

    // Note, it's safe to call unwrap() because the arg is required
    let port: u16 = *matches
        .get_one::<u16>("PORT")
        .expect("'PORT' is required and parsing will fail if its missing");
    println!("PORT = {}", port);
}
examples/tutorial_builder/04_02_parse.rs (line 8)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            arg!(<PORT>)
                .help("Network port to use")
                .value_parser(value_parser!(u16).range(1..)),
        )
        .get_matches();

    // Note, it's safe to call unwrap() because the arg is required
    let port: u16 = *matches
        .get_one::<u16>("PORT")
        .expect("'PORT' is required and parsing will fail if its missing");
    println!("PORT = {}", port);
}
examples/tutorial_builder/04_01_enum.rs (line 50)
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            arg!(<MODE>)
                .help("What mode to run the program in")
                .value_parser(value_parser!(Mode)),
        )
        .get_matches();

    // Note, it's safe to call unwrap() because the arg is required
    match matches
        .get_one::<Mode>("MODE")
        .expect("'MODE' is required and parsing will fail if its missing")
    {
        Mode::Fast => {
            println!("Hare");
        }
        Mode::Slow => {
            println!("Tortoise");
        }
    }
}
examples/tutorial_builder/04_01_possible.rs (line 8)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            arg!(<MODE>)
                .help("What mode to run the program in")
                .value_parser(["fast", "slow"]),
        )
        .get_matches();

    // Note, it's safe to call unwrap() because the arg is required
    match matches
        .get_one::<String>("MODE")
        .expect("'MODE' is required and parsing will fail if its missing")
        .as_str()
    {
        "fast" => {
            println!("Hare");
        }
        "slow" => {
            println!("Tortoise");
        }
        _ => unreachable!(),
    }
}
examples/cargo-example.rs (line 9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fn main() {
    let cmd = clap::Command::new("cargo")
        .bin_name("cargo")
        .subcommand_required(true)
        .subcommand(
            clap::command!("example").arg(
                clap::arg!(--"manifest-path" <PATH>)
                    .required(false)
                    .value_parser(clap::value_parser!(std::path::PathBuf)),
            ),
        );
    let matches = cmd.get_matches();
    let matches = match matches.subcommand() {
        Some(("example", matches)) => matches,
        _ => unreachable!("clap should ensure we don't get here"),
    };
    let manifest_path = matches.get_one::<std::path::PathBuf>("manifest-path");
    println!("{:?}", manifest_path);
}

Specifies that the argument may have an unknown number of values

Without any other settings, this argument may appear only once.

For example, --opt val1 val2 is allowed, but --opt val1 val2 --opt val3 is not.

NOTE: Setting this requires Arg::takes_value.

WARNING:

Setting multiple_values for an argument that takes a value, but with no other details can be dangerous in some circumstances. Because multiple values are allowed, --option val1 val2 val3 is perfectly valid. Be careful when designing a CLI where positional arguments are also expected as clap will continue parsing values until one of the following happens:

Alternatively, require a delimiter between values.

WARNING:

When using args with multiple_values and subcommands, one needs to consider the possibility of an argument value being the same as a valid subcommand. By default clap will parse the argument in question as a value only if a value is possible at that moment. Otherwise it will be parsed as a subcommand. In effect, this means using multiple_values with no additional parameters and a value that coincides with a subcommand name, the subcommand cannot be called unless another argument is passed between them.

As an example, consider a CLI with an option --ui-paths=<paths>... and subcommand signer

The following would be parsed as values to --ui-paths.

$ program --ui-paths path1 path2 signer

This is because --ui-paths accepts multiple values. clap will continue parsing values until another argument is reached and it knows --ui-paths is done parsing.

By adding additional parameters to --ui-paths we can solve this issue. Consider adding Arg::number_of_values(1) or using only ArgAction::Append. The following are all valid, and signer is parsed as a subcommand in the first case, but a value in the second case.

$ program --ui-paths path1 signer
$ program --ui-paths path1 --ui-paths signer signer
Examples

An example with options

let m = Command::new("prog")
    .arg(Arg::new("file")
        .takes_value(true)
        .multiple_values(true)
        .short('F'))
    .get_matches_from(vec![
        "prog", "-F", "file1", "file2", "file3"
    ]);

assert!(m.contains_id("file"));
let files: Vec<_> = m.values_of("file").unwrap().collect();
assert_eq!(files, ["file1", "file2", "file3"]);

Although multiple_values has been specified, we cannot use the argument more than once.

let res = Command::new("prog")
    .arg(Arg::new("file")
        .takes_value(true)
        .multiple_values(true)
        .short('F'))
    .try_get_matches_from(vec![
        "prog", "-F", "file1", "-F", "file2", "-F", "file3"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::UnexpectedMultipleUsage)

A common mistake is to define an option which allows multiple values, and a positional argument.

let m = Command::new("prog")
    .arg(Arg::new("file")
        .takes_value(true)
        .multiple_values(true)
        .short('F'))
    .arg(Arg::new("word"))
    .get_matches_from(vec![
        "prog", "-F", "file1", "file2", "file3", "word"
    ]);

assert!(m.contains_id("file"));
let files: Vec<_> = m.values_of("file").unwrap().collect();
assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?!
assert!(!m.contains_id("word")); // but we clearly used word!

The problem is clap doesn’t know when to stop parsing values for “files”. This is further compounded by if we’d said word -F file1 file2 it would have worked fine, so it would appear to only fail sometimes…not good!

A solution for the example above is to limit how many values with a maximum, or specific number, or to say ArgAction::Append is ok, but multiple values is not.

let m = Command::new("prog")
    .arg(Arg::new("file")
        .takes_value(true)
        .action(ArgAction::Append)
        .short('F'))
    .arg(Arg::new("word"))
    .get_matches_from(vec![
        "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word"
    ]);

assert!(m.contains_id("file"));
let files: Vec<_> = m.values_of("file").unwrap().collect();
assert_eq!(files, ["file1", "file2", "file3"]);
assert!(m.contains_id("word"));
assert_eq!(m.value_of("word"), Some("word"));

As a final example, let’s fix the above error and get a pretty message to the user :)

let res = Command::new("prog")
    .arg(Arg::new("file")
        .takes_value(true)
        .action(ArgAction::Append)
        .short('F'))
    .arg(Arg::new("word"))
    .try_get_matches_from(vec![
        "prog", "-F", "file1", "file2", "file3", "word"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
Examples found in repository?
examples/escaped-positional.rs (line 14)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(arg!(eff: -f).action(ArgAction::SetTrue))
        .arg(
            arg!(pea: -p <PEAR>)
                .required(false)
                .value_parser(value_parser!(String)),
        )
        .arg(
            // Indicates that `slop` is only accessible after `--`.
            arg!(slop: [SLOP])
                .multiple_values(true)
                .last(true)
                .value_parser(value_parser!(String)),
        )
        .get_matches();

    // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`...

    // -f used: true
    println!("-f used: {:?}", matches.get_flag("eff"));
    // -p's value: Some("bob")
    println!("-p's value: {:?}", matches.get_one::<String>("pea"));
    // 'slops' values: Some(["sloppy", "slop", "slop"])
    println!(
        "'slops' values: {:?}",
        matches
            .get_many::<String>("slop")
            .map(|vals| vals.collect::<Vec<_>>())
            .unwrap_or_default()
    );

    // Continued program logic goes here...
}
More examples
Hide additional examples
examples/pacman.rs (line 25)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
fn main() {
    let matches = Command::new("pacman")
        .about("package manager utility")
        .version("5.2.1")
        .subcommand_required(true)
        .arg_required_else_help(true)
        .author("Pacman Development Team")
        // Query subcommand
        //
        // Only a few of its arguments are implemented below.
        .subcommand(
            Command::new("query")
                .short_flag('Q')
                .long_flag("query")
                .about("Query the package database.")
                .arg(
                    Arg::new("search")
                        .short('s')
                        .long("search")
                        .help("search locally installed packages for matching strings")
                        .conflicts_with("info")
                        .takes_value(true)
                        .multiple_values(true),
                )
                .arg(
                    Arg::new("info")
                        .long("info")
                        .short('i')
                        .conflicts_with("search")
                        .help("view package information")
                        .takes_value(true)
                        .multiple_values(true),
                ),
        )
        // Sync subcommand
        //
        // Only a few of its arguments are implemented below.
        .subcommand(
            Command::new("sync")
                .short_flag('S')
                .long_flag("sync")
                .about("Synchronize packages.")
                .arg(
                    Arg::new("search")
                        .short('s')
                        .long("search")
                        .conflicts_with("info")
                        .takes_value(true)
                        .multiple_values(true)
                        .help("search remote repositories for matching strings"),
                )
                .arg(
                    Arg::new("info")
                        .long("info")
                        .conflicts_with("search")
                        .short('i')
                        .action(ArgAction::SetTrue)
                        .help("view package information"),
                )
                .arg(
                    Arg::new("package")
                        .help("packages")
                        .required_unless_present("search")
                        .takes_value(true)
                        .multiple_values(true),
                ),
        )
        .get_matches();

    match matches.subcommand() {
        Some(("sync", sync_matches)) => {
            if sync_matches.contains_id("search") {
                let packages: Vec<_> = sync_matches
                    .get_many::<String>("search")
                    .expect("contains_id")
                    .map(|s| s.as_str())
                    .collect();
                let values = packages.join(", ");
                println!("Searching for {}...", values);
                return;
            }

            let packages: Vec<_> = sync_matches
                .get_many::<String>("package")
                .expect("is present")
                .map(|s| s.as_str())
                .collect();
            let values = packages.join(", ");

            if sync_matches.get_flag("info") {
                println!("Retrieving info for {}...", values);
            } else {
                println!("Installing {}...", values);
            }
        }
        Some(("query", query_matches)) => {
            if let Some(packages) = query_matches.get_many::<String>("info") {
                let comma_sep = packages.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
                println!("Retrieving info for {}...", comma_sep);
            } else if let Some(queries) = query_matches.get_many::<String>("search") {
                let comma_sep = queries.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
                println!("Searching Locally for {}...", comma_sep);
            } else {
                println!("Displaying all locally installed packages...");
            }
        }
        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
    }
}

The number of values allowed for this argument.

For example, if you had a -f <file> argument where you wanted exactly 3 ‘files’ you would set .number_of_values(3), and this argument wouldn’t be satisfied unless the user provided 3 and only 3 values.

NOTE: Does not require Arg::multiple_occurrences(true) to be set. Setting Arg::multiple_occurrences(true) would allow -f <file> <file> <file> -f <file> <file> <file> where as not setting it would only allow one occurrence of this argument.

NOTE: implicitly sets [Arg::takes_value(true)] and [Arg::multiple_values(true)].

Examples
Arg::new("file")
    .short('f')
    .number_of_values(3);

Not supplying the correct number of values is an error

let res = Command::new("prog")
    .arg(Arg::new("file")
        .takes_value(true)
        .number_of_values(2)
        .short('F'))
    .try_get_matches_from(vec![
        "prog", "-F", "file1"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::WrongNumberOfValues);

The maximum number of values are for this argument.

For example, if you had a -f <file> argument where you wanted up to 3 ‘files’ you would set .max_values(3), and this argument would be satisfied if the user provided, 1, 2, or 3 values.

NOTE: This does not implicitly set Arg::multiple_occurrences(true). This is because -o val -o val is multiple occurrences but a single value and -o val1 val2 is a single occurrence with multiple values. For positional arguments this does set Arg::multiple_occurrences(true) because there is no way to determine the difference between multiple occurrences and multiple values.

Examples
Arg::new("file")
    .short('f')
    .max_values(3);

Supplying less than the maximum number of values is allowed

let res = Command::new("prog")
    .arg(Arg::new("file")
        .takes_value(true)
        .max_values(3)
        .short('F'))
    .try_get_matches_from(vec![
        "prog", "-F", "file1", "file2"
    ]);

assert!(res.is_ok());
let m = res.unwrap();
let files: Vec<_> = m.values_of("file").unwrap().collect();
assert_eq!(files, ["file1", "file2"]);

Supplying more than the maximum number of values is an error

let res = Command::new("prog")
    .arg(Arg::new("file")
        .takes_value(true)
        .max_values(2)
        .short('F'))
    .try_get_matches_from(vec![
        "prog", "-F", "file1", "file2", "file3"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);

The minimum number of values for this argument.

For example, if you had a -f <file> argument where you wanted at least 2 ‘files’ you would set .min_values(2), and this argument would be satisfied if the user provided, 2 or more values.

NOTE: This does not implicitly set Arg::multiple_occurrences(true). This is because -o val -o val is multiple occurrences but a single value and -o val1 val2 is a single occurrence with multiple values. For positional arguments this does set Arg::multiple_occurrences(true) because there is no way to determine the difference between multiple occurrences and multiple values.

NOTE: Passing a non-zero value is not the same as specifying Arg::required(true). This is due to min and max validation only being performed for present arguments, marking them as required will thus perform validation and a min value of 1 is unnecessary, ignored if not required.

Examples
Arg::new("file")
    .short('f')
    .min_values(3);

Supplying more than the minimum number of values is allowed

let res = Command::new("prog")
    .arg(Arg::new("file")
        .takes_value(true)
        .min_values(2)
        .short('F'))
    .try_get_matches_from(vec![
        "prog", "-F", "file1", "file2", "file3"
    ]);

assert!(res.is_ok());
let m = res.unwrap();
let files: Vec<_> = m.values_of("file").unwrap().collect();
assert_eq!(files, ["file1", "file2", "file3"]);

Supplying less than the minimum number of values is an error

let res = Command::new("prog")
    .arg(Arg::new("file")
        .takes_value(true)
        .min_values(2)
        .short('F'))
    .try_get_matches_from(vec![
        "prog", "-F", "file1"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::TooFewValues);

Placeholder for the argument’s value in the help message / usage.

This name is cosmetic only; the name is not used to access arguments. This setting can be very helpful when describing the type of input the user should be using, such as FILE, INTERFACE, etc. Although not required, it’s somewhat convention to use all capital letters for the value name.

NOTE: implicitly sets Arg::takes_value(true)

Examples
Arg::new("cfg")
    .long("config")
    .value_name("FILE")
let m = Command::new("prog")
    .arg(Arg::new("config")
        .long("config")
        .value_name("FILE")
        .help("Some help text"))
    .get_matches_from(vec![
        "prog", "--help"
    ]);

Running the above program produces the following output

valnames

USAGE:
   valnames [OPTIONS]

OPTIONS:
    --config <FILE>     Some help text
    -h, --help          Print help information
    -V, --version       Print version information

Placeholders for the argument’s values in the help message / usage.

These names are cosmetic only, used for help and usage strings only. The names are not used to access arguments. The values of the arguments are accessed in numeric order (i.e. if you specify two names one and two one will be the first matched value, two will be the second).

This setting can be very helpful when describing the type of input the user should be using, such as FILE, INTERFACE, etc. Although not required, it’s somewhat convention to use all capital letters for the value name.

Pro Tip: It may help to use Arg::next_line_help(true) if there are long, or multiple value names in order to not throw off the help text alignment of all options.

NOTE: implicitly sets Arg::takes_value(true) and Arg::multiple_values(true).

Examples
Arg::new("speed")
    .short('s')
    .value_names(&["fast", "slow"]);
let m = Command::new("prog")
    .arg(Arg::new("io")
        .long("io-files")
        .value_names(&["INFILE", "OUTFILE"]))
    .get_matches_from(vec![
        "prog", "--help"
    ]);

Running the above program produces the following output

valnames

USAGE:
   valnames [OPTIONS]

OPTIONS:
    -h, --help                       Print help information
    --io-files <INFILE> <OUTFILE>    Some help text
    -V, --version                    Print version information

Provide the shell a hint about how to complete this argument.

See ValueHint for more information.

NOTE: implicitly sets [Arg::takes_value(true)].

For example, to take a username as argument:

Arg::new("user")
    .short('u')
    .long("user")
    .value_hint(ValueHint::Username);

To take a full command line and its arguments (for example, when writing a command wrapper):

Command::new("prog")
    .trailing_var_arg(true)
    .arg(
        Arg::new("command")
            .takes_value(true)
            .multiple_values(true)
            .value_hint(ValueHint::CommandWithArguments)
    );

Deprecated, replaced with [Arg::value_parser(...)]

Derive: replace #[clap(validator = ...)] with #[clap(value_parser = ...)]

Builder: replace arg.validator(...) with arg.value_parser(...) and matches.value_of with matches.get_one::<T> or matches.values_of with matches.get_many::<T>

Deprecated, replaced with [Arg::value_parser(...)]

Available on crate feature regex only.

Deprecated in Issue #3743, replaced with [Arg::value_parser(...)]

Derive: replace #[clap(validator_regex = ...)] with #[clap(value_parser = |s: &str| regex.is_match(s).then(|| s.to_owned()).ok_or_else(|| ...))]

Builder: replace arg.validator_regex(...) with arg.value_parser(|s: &str| regex.is_match(s).then(|| s.to_owned()).ok_or_else(|| ...))

Deprecated, replaced with [Arg::value_parser(PossibleValuesParser::new(...))]

Derive: replace #[clap(possible_value = <1>, possible_value = <2>, ...)] with #[clap(value_parser = [<1>, <2>])]. If the field is not a String, instead do #[clap(value_parser = PossibleValueParser::new([<1>, <2>]).map(T::from_str))]

Builder: replace arg.possible_value(<1>).possible_value(<2>) with arg.value_parser([<1>, <2>])`

Deprecated, replaced with [Arg::value_parser(PossibleValuesParser::new(...))]

Derive: replace #[clap(possible_values = [<1>, <2>])] with #[clap(value_parser = [<1>, <2>])]. If the field is not a String, instead do #[clap(value_parser = PossibleValueParser::new([<1>, <2>]).map(T::from_str))]

Builder: replace arg.possible_values([<1>, <2>) with arg.value_parser([<1>, <2>])`

Match values against Arg::possible_values without matching case.

When other arguments are conditionally required based on the value of a case-insensitive argument, the equality check done by Arg::required_if_eq, Arg::required_if_eq_any, or Arg::required_if_eq_all is case-insensitive.

NOTE: Setting this requires Arg::takes_value

NOTE: To do unicode case folding, enable the unicode feature flag.

Examples
let m = Command::new("pv")
    .arg(Arg::new("option")
        .long("option")
        .takes_value(true)
        .ignore_case(true)
        .value_parser(["test123"]))
    .get_matches_from(vec![
        "pv", "--option", "TeSt123",
    ]);

assert!(m.value_of("option").unwrap().eq_ignore_ascii_case("test123"));

This setting also works when multiple values can be defined:

let m = Command::new("pv")
    .arg(Arg::new("option")
        .short('o')
        .long("option")
        .takes_value(true)
        .ignore_case(true)
        .multiple_values(true)
        .value_parser(["test123", "test321"]))
    .get_matches_from(vec![
        "pv", "--option", "TeSt123", "teST123", "tESt321"
    ]);

let matched_vals = m.values_of("option").unwrap().collect::<Vec<_>>();
assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]);

Allows values which start with a leading hyphen (-)

NOTE: Setting this requires Arg::takes_value

WARNING: Take caution when using this setting combined with Arg::multiple_values, as this becomes ambiguous $ prog --arg -- -- val. All three --, --, val will be values when the user may have thought the second -- would constitute the normal, “Only positional args follow” idiom. To fix this, consider using Arg::multiple_occurrences which only allows a single value at a time.

WARNING: When building your CLIs, consider the effects of allowing leading hyphens and the user passing in a value that matches a valid short. For example, prog -opt -F where -F is supposed to be a value, yet -F is also a valid short for another arg. Care should be taken when designing these args. This is compounded by the ability to “stack” short args. I.e. if -val is supposed to be a value, but -v, -a, and -l are all valid shorts.

Examples
let m = Command::new("prog")
    .arg(Arg::new("pat")
        .takes_value(true)
        .allow_hyphen_values(true)
        .long("pattern"))
    .get_matches_from(vec![
        "prog", "--pattern", "-file"
    ]);

assert_eq!(m.value_of("pat"), Some("-file"));

Not setting Arg::allow_hyphen_values(true) and supplying a value which starts with a hyphen is an error.

let res = Command::new("prog")
    .arg(Arg::new("pat")
        .takes_value(true)
        .long("pattern"))
    .try_get_matches_from(vec![
        "prog", "--pattern", "-file"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);

Deprecated, replaced with value_parser

Derive: replace #[clap(allow_invalid_utf8 = true)] with #[clap(action)] (which opts-in to the new clap v4 behavior which gets the type via value_parser!)

Builder: replace arg.allow_invalid_utf8(true) with arg.value_parser(value_parser!(T)) where T is the type of interest, like OsString or PathBuf, and matches.value_of_os with matches.get_one::<T> or matches.values_of_os with matches.get_many::<T>

Deprecated, replaced with [Arg::value_parser(NonEmptyStringValueParser::new())]

Derive: replace #[clap(forbid_empty_values = true)] with #[clap(value_parser = NonEmptyStringValueParser::new())]

Builder: replace arg.forbid_empty_values(true) with arg.value_parser(NonEmptyStringValueParser::new())

Requires that options use the --option=val syntax

i.e. an equals between the option and associated value.

NOTE: Setting this requires Arg::takes_value

Examples

Setting require_equals requires that the option have an equals sign between it and the associated value.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .takes_value(true)
        .require_equals(true)
        .long("config"))
    .try_get_matches_from(vec![
        "prog", "--config=file.conf"
    ]);

assert!(res.is_ok());

Setting require_equals and not supplying the equals will cause an error.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .takes_value(true)
        .require_equals(true)
        .long("config"))
    .try_get_matches_from(vec![
        "prog", "--config", "file.conf"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals);

Specifies that an argument should allow grouping of multiple values via a delimiter.

i.e. should --option=val1,val2,val3 be parsed as three values (val1, val2, and val3) or as a single value (val1,val2,val3). Defaults to using , (comma) as the value delimiter for all arguments that accept values (options and positional arguments)

NOTE: When this setting is used, it will default Arg::value_delimiter to the comma ,.

NOTE: Implicitly sets Arg::takes_value

Examples

The following example shows the default behavior.

let delims = Command::new("prog")
    .arg(Arg::new("option")
        .long("option")
        .use_value_delimiter(true)
        .takes_value(true))
    .get_matches_from(vec![
        "prog", "--option=val1,val2,val3",
    ]);

assert!(delims.contains_id("option"));
assert_eq!(delims.values_of("option").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);

The next example shows the difference when turning delimiters off. This is the default behavior

let nodelims = Command::new("prog")
    .arg(Arg::new("option")
        .long("option")
        .takes_value(true))
    .get_matches_from(vec![
        "prog", "--option=val1,val2,val3",
    ]);

assert!(nodelims.contains_id("option"));
assert_eq!(nodelims.value_of("option").unwrap(), "val1,val2,val3");
Examples found in repository?
examples/multicall-busybox.rs (line 29)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
fn main() {
    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
        .multicall(true)
        .subcommand(
            Command::new("busybox")
                .arg_required_else_help(true)
                .subcommand_value_name("APPLET")
                .subcommand_help_heading("APPLETS")
                .arg(
                    Arg::new("install")
                        .long("install")
                        .help("Install hardlinks for all subcommands in path")
                        .exclusive(true)
                        .takes_value(true)
                        .default_missing_value("/usr/local/bin")
                        .value_parser(value_parser!(PathBuf))
                        .use_value_delimiter(false),
                )
                .subcommands(applet_commands()),
        )
        .subcommands(applet_commands());

    let matches = cmd.get_matches();
    let mut subcommand = matches.subcommand();
    if let Some(("busybox", cmd)) = subcommand {
        if cmd.contains_id("install") {
            unimplemented!("Make hardlinks to the executable here");
        }
        subcommand = cmd.subcommand();
    }
    match subcommand {
        Some(("false", _)) => exit(1),
        Some(("true", _)) => exit(0),
        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    }
}

Deprecated, replaced with Arg::use_value_delimiter

Derive: replace #[clap(use_delimiter = true)] with #[clap(use_value_delimiter = true)]

Builder: replace arg.use_delimiter(true) with arg.use_value_delimiter(true)

Separator between the arguments values, defaults to , (comma).

NOTE: implicitly sets Arg::use_value_delimiter(true)

NOTE: implicitly sets Arg::takes_value(true)

Examples
let m = Command::new("prog")
    .arg(Arg::new("config")
        .short('c')
        .long("config")
        .value_delimiter(';'))
    .get_matches_from(vec![
        "prog", "--config=val1;val2;val3"
    ]);

assert_eq!(m.values_of("config").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"])

Specifies that multiple values may only be set using the delimiter.

This means if an option is encountered, and no delimiter is found, it is assumed that no additional values for that option follow. This is unlike the default, where it is generally assumed that more values will follow regardless of whether or not a delimiter is used.

NOTE: The default is false.

NOTE: Setting this requires Arg::use_value_delimiter and Arg::takes_value

NOTE: It’s a good idea to inform the user that use of a delimiter is required, either through help text or other means.

Examples

These examples demonstrate what happens when require_delimiter(true) is used. Notice everything works in this first example, as we use a delimiter, as expected.

let delims = Command::new("prog")
    .arg(Arg::new("opt")
        .short('o')
        .takes_value(true)
        .use_value_delimiter(true)
        .require_delimiter(true)
        .multiple_values(true))
    .get_matches_from(vec![
        "prog", "-o", "val1,val2,val3",
    ]);

assert!(delims.contains_id("opt"));
assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);

In this next example, we will not use a delimiter. Notice it’s now an error.

let res = Command::new("prog")
    .arg(Arg::new("opt")
        .short('o')
        .takes_value(true)
        .use_value_delimiter(true)
        .require_delimiter(true))
    .try_get_matches_from(vec![
        "prog", "-o", "val1", "val2", "val3",
    ]);

assert!(res.is_err());
let err = res.unwrap_err();
assert_eq!(err.kind(), ErrorKind::UnknownArgument);

What’s happening is -o is getting val1, and because delimiters are required yet none were present, it stops parsing -o. At this point it reaches val2 and because no positional arguments have been defined, it’s an error of an unexpected argument.

In this final example, we contrast the above with clap’s default behavior where the above is not an error.

let delims = Command::new("prog")
    .arg(Arg::new("opt")
        .short('o')
        .takes_value(true)
        .multiple_values(true))
    .get_matches_from(vec![
        "prog", "-o", "val1", "val2", "val3",
    ]);

assert!(delims.contains_id("opt"));
assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);

Deprecated, replaced with Arg::require_value_delimiter

Derive: replace #[clap(require_delimiter = true)] with #[clap(require_value_delimiter = true)]

Builder: replace arg.require_delimiter(true) with arg.require_value_delimiter(true)

Sentinel to stop parsing multiple values of a give argument.

By default when one sets multiple_values(true) on an argument, clap will continue parsing values for that argument until it reaches another valid argument, or one of the other more specific settings for multiple values is used (such as min_values, max_values or number_of_values).

NOTE: This setting only applies to options and positional arguments

NOTE: When the terminator is passed in on the command line, it is not stored as one of the values

Examples
Arg::new("vals")
    .takes_value(true)
    .multiple_values(true)
    .value_terminator(";")

The following example uses two arguments, a sequence of commands, and the location in which to perform them

let m = Command::new("prog")
    .arg(Arg::new("cmds")
        .takes_value(true)
        .multiple_values(true)
        .allow_hyphen_values(true)
        .value_terminator(";"))
    .arg(Arg::new("location"))
    .get_matches_from(vec![
        "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap"
    ]);
let cmds: Vec<_> = m.values_of("cmds").unwrap().collect();
assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]);
assert_eq!(m.value_of("location"), Some("/home/clap"));

Consume all following arguments.

Do not be parse them individually, but rather pass them in entirety.

It is worth noting that setting this requires all values to come after a -- to indicate they should all be captured. For example:

--foo something -- -v -v -v -b -b -b --baz -q -u -x

Will result in everything after -- to be considered one raw argument. This behavior may not be exactly what you are expecting and using crate::Command::trailing_var_arg may be more appropriate.

NOTE: Implicitly sets Arg::takes_value(true) Arg::multiple_values(true), Arg::allow_hyphen_values(true), and Arg::last(true) when set to true.

Value for the argument when not present.

NOTE: If the user does not use this argument at runtime, ArgMatches::occurrences_of will return 0 even though the ArgMatches::value_of will return the default specified.

NOTE: If the user does not use this argument at runtime ArgMatches::contains_id will still return true. If you wish to determine whether the argument was used at runtime or not, consider ArgMatches::value_source.

NOTE: This setting is perfectly compatible with Arg::default_value_if but slightly different. Arg::default_value only takes effect when the user has not provided this arg at runtime. Arg::default_value_if however only takes effect when the user has not provided a value at runtime and these other conditions are met as well. If you have set Arg::default_value and Arg::default_value_if, and the user did not provide this arg at runtime, nor were the conditions met for Arg::default_value_if, the Arg::default_value will be applied.

NOTE: This implicitly sets Arg::takes_value(true).

Examples

First we use the default value without providing any value at runtime.

let m = Command::new("prog")
    .arg(Arg::new("opt")
        .long("myopt")
        .default_value("myval"))
    .get_matches_from(vec![
        "prog"
    ]);

assert_eq!(m.value_of("opt"), Some("myval"));
assert!(m.contains_id("opt"));
assert_eq!(m.value_source("opt"), Some(ValueSource::DefaultValue));

Next we provide a value at runtime to override the default.

let m = Command::new("prog")
    .arg(Arg::new("opt")
        .long("myopt")
        .default_value("myval"))
    .get_matches_from(vec![
        "prog", "--myopt=non_default"
    ]);

assert_eq!(m.value_of("opt"), Some("non_default"));
assert!(m.contains_id("opt"));
assert_eq!(m.value_source("opt"), Some(ValueSource::CommandLine));
Examples found in repository?
examples/tutorial_builder/03_05_default_values.rs (line 5)
3
4
5
6
7
8
9
10
11
12
13
14
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(arg!([NAME]).default_value("alice"))
        .get_matches();

    println!(
        "NAME: {:?}",
        matches
            .get_one::<String>("NAME")
            .expect("default ensures there is always a value")
    );
}

Value for the argument when not present.

See Arg::default_value.

Value for the argument when not present.

See Arg::default_value.

Value for the argument when not present.

See Arg::default_values.

Value for the argument when the flag is present but no value is specified.

This configuration option is often used to give the user a shortcut and allow them to efficiently specify an option argument without requiring an explicitly value. The --color argument is a common example. By, supplying an default, such as default_missing_value("always"), the user can quickly just add --color to the command line to produce the desired color output.

NOTE: using this configuration option requires the use of the .min_values(0) and the .require_equals(true) configuration option. These are required in order to unambiguously determine what, if any, value was supplied for the argument.

Examples

For POSIX style --color:

fn cli() -> Command<'static> {
    Command::new("prog")
        .arg(Arg::new("color").long("color")
            .value_name("WHEN")
            .value_parser(["always", "auto", "never"])
            .default_value("auto")
            .min_values(0)
            .require_equals(true)
            .default_missing_value("always")
            .help("Specify WHEN to colorize output.")
        )
}

// first, we'll provide no arguments
let m  = cli().get_matches_from(vec![
        "prog"
    ]);
assert_eq!(m.value_of("color"), Some("auto"));
assert_eq!(m.value_source("color"), Some(ValueSource::DefaultValue));

// next, we'll provide a runtime value to override the default (as usually done).
let m  = cli().get_matches_from(vec![
        "prog", "--color=never"
    ]);
assert_eq!(m.value_of("color"), Some("never"));
assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine));

// finally, we will use the shortcut and only provide the argument without a value.
let m  = cli().get_matches_from(vec![
        "prog", "--color"
    ]);
assert_eq!(m.value_of("color"), Some("always"));
assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine));

For bool literals:

fn cli() -> Command<'static> {
    Command::new("prog")
        .arg(Arg::new("create").long("create")
            .value_name("BOOL")
            .value_parser(value_parser!(bool))
            .min_values(0)
            .require_equals(true)
            .default_missing_value("true")
        )
}

// first, we'll provide no arguments
let m  = cli().get_matches_from(vec![
        "prog"
    ]);
assert_eq!(m.get_one::<bool>("create").copied(), None);

// next, we'll provide a runtime value to override the default (as usually done).
let m  = cli().get_matches_from(vec![
        "prog", "--create=false"
    ]);
assert_eq!(m.get_one::<bool>("create").copied(), Some(false));
assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine));

// finally, we will use the shortcut and only provide the argument without a value.
let m  = cli().get_matches_from(vec![
        "prog", "--create"
    ]);
assert_eq!(m.get_one::<bool>("create").copied(), Some(true));
assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine));
Examples found in repository?
examples/multicall-busybox.rs (line 27)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
fn main() {
    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
        .multicall(true)
        .subcommand(
            Command::new("busybox")
                .arg_required_else_help(true)
                .subcommand_value_name("APPLET")
                .subcommand_help_heading("APPLETS")
                .arg(
                    Arg::new("install")
                        .long("install")
                        .help("Install hardlinks for all subcommands in path")
                        .exclusive(true)
                        .takes_value(true)
                        .default_missing_value("/usr/local/bin")
                        .value_parser(value_parser!(PathBuf))
                        .use_value_delimiter(false),
                )
                .subcommands(applet_commands()),
        )
        .subcommands(applet_commands());

    let matches = cmd.get_matches();
    let mut subcommand = matches.subcommand();
    if let Some(("busybox", cmd)) = subcommand {
        if cmd.contains_id("install") {
            unimplemented!("Make hardlinks to the executable here");
        }
        subcommand = cmd.subcommand();
    }
    match subcommand {
        Some(("false", _)) => exit(1),
        Some(("true", _)) => exit(0),
        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    }
}

Value for the argument when the flag is present but no value is specified.

See Arg::default_missing_value.

Value for the argument when the flag is present but no value is specified.

See Arg::default_missing_value.

Value for the argument when the flag is present but no value is specified.

See Arg::default_missing_values.

Available on crate feature env only.

Read from name environment variable when argument is not present.

If it is not present in the environment, then default rules will apply.

If user sets the argument in the environment:

If user doesn’t set the argument in the environment:

Examples

In this example, we show the variable coming from the environment:


env::set_var("MY_FLAG", "env");

let m = Command::new("prog")
    .arg(Arg::new("flag")
        .long("flag")
        .env("MY_FLAG")
        .takes_value(true))
    .get_matches_from(vec![
        "prog"
    ]);

assert_eq!(m.value_of("flag"), Some("env"));

In this example, because [Arg::takes_value(false)] (by default), prog is a flag that accepts an optional, case-insensitive boolean literal. A false literal is n, no, f, false, off or 0. An absent environment variable will also be considered as false. Anything else will considered as true.


env::set_var("TRUE_FLAG", "true");
env::set_var("FALSE_FLAG", "0");

let m = Command::new("prog")
    .arg(Arg::new("true_flag")
        .long("true_flag")
        .env("TRUE_FLAG"))
    .arg(Arg::new("false_flag")
        .long("false_flag")
        .env("FALSE_FLAG"))
    .arg(Arg::new("absent_flag")
        .long("absent_flag")
        .env("ABSENT_FLAG"))
    .get_matches_from(vec![
        "prog"
    ]);

assert!(m.is_present("true_flag"));
assert_eq!(m.value_of("true_flag"), None);
assert!(!m.is_present("false_flag"));
assert!(!m.is_present("absent_flag"));

In this example, we show the variable coming from an option on the CLI:


env::set_var("MY_FLAG", "env");

let m = Command::new("prog")
    .arg(Arg::new("flag")
        .long("flag")
        .env("MY_FLAG")
        .takes_value(true))
    .get_matches_from(vec![
        "prog", "--flag", "opt"
    ]);

assert_eq!(m.value_of("flag"), Some("opt"));

In this example, we show the variable coming from the environment even with the presence of a default:


env::set_var("MY_FLAG", "env");

let m = Command::new("prog")
    .arg(Arg::new("flag")
        .long("flag")
        .env("MY_FLAG")
        .takes_value(true)
        .default_value("default"))
    .get_matches_from(vec![
        "prog"
    ]);

assert_eq!(m.value_of("flag"), Some("env"));

In this example, we show the use of multiple values in a single environment variable:


env::set_var("MY_FLAG_MULTI", "env1,env2");

let m = Command::new("prog")
    .arg(Arg::new("flag")
        .long("flag")
        .env("MY_FLAG_MULTI")
        .takes_value(true)
        .multiple_values(true)
        .use_value_delimiter(true))
    .get_matches_from(vec![
        "prog"
    ]);

assert_eq!(m.values_of("flag").unwrap().collect::<Vec<_>>(), vec!["env1", "env2"]);
Available on crate feature env only.

Read from name environment variable when argument is not present.

See Arg::env.

Sets the description of the argument for short help (-h).

Typically, this is a short (one line) description of the arg.

If Arg::long_help is not specified, this message will be displayed for --help.

NOTE: Only Arg::help is used in completion script generation in order to be concise

Examples

Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to include a newline in the help text and have the following text be properly aligned with all the other help text.

Setting help displays a short message to the side of the argument when the user passes -h or --help (by default).

let m = Command::new("prog")
    .arg(Arg::new("cfg")
        .long("config")
        .help("Some help text describing the --config arg"))
    .get_matches_from(vec![
        "prog", "--help"
    ]);

The above example displays

helptest

USAGE:
   helptest [OPTIONS]

OPTIONS:
    --config     Some help text describing the --config arg
-h, --help       Print help information
-V, --version    Print version information
Examples found in repository?
examples/tutorial_builder/05_01_assert.rs (line 17)
13
14
15
16
17
18
19
20
fn cmd() -> clap::Command<'static> {
    command!() // requires `cargo` feature
        .arg(
            arg!(<PORT>)
                .help("Network port to use")
                .value_parser(value_parser!(usize)),
        )
}
More examples
Hide additional examples
examples/tutorial_builder/04_02_validate.rs (line 9)
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            arg!(<PORT>)
                .help("Network port to use")
                .value_parser(port_in_range),
        )
        .get_matches();

    // Note, it's safe to call unwrap() because the arg is required
    let port: u16 = *matches
        .get_one::<u16>("PORT")
        .expect("'PORT' is required and parsing will fail if its missing");
    println!("PORT = {}", port);
}
examples/tutorial_builder/04_02_parse.rs (line 7)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            arg!(<PORT>)
                .help("Network port to use")
                .value_parser(value_parser!(u16).range(1..)),
        )
        .get_matches();

    // Note, it's safe to call unwrap() because the arg is required
    let port: u16 = *matches
        .get_one::<u16>("PORT")
        .expect("'PORT' is required and parsing will fail if its missing");
    println!("PORT = {}", port);
}
examples/tutorial_builder/04_01_enum.rs (line 49)
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            arg!(<MODE>)
                .help("What mode to run the program in")
                .value_parser(value_parser!(Mode)),
        )
        .get_matches();

    // Note, it's safe to call unwrap() because the arg is required
    match matches
        .get_one::<Mode>("MODE")
        .expect("'MODE' is required and parsing will fail if its missing")
    {
        Mode::Fast => {
            println!("Hare");
        }
        Mode::Slow => {
            println!("Tortoise");
        }
    }
}
examples/tutorial_builder/04_01_possible.rs (line 7)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            arg!(<MODE>)
                .help("What mode to run the program in")
                .value_parser(["fast", "slow"]),
        )
        .get_matches();

    // Note, it's safe to call unwrap() because the arg is required
    match matches
        .get_one::<String>("MODE")
        .expect("'MODE' is required and parsing will fail if its missing")
        .as_str()
    {
        "fast" => {
            println!("Hare");
        }
        "slow" => {
            println!("Tortoise");
        }
        _ => unreachable!(),
    }
}
examples/multicall-busybox.rs (line 24)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
fn main() {
    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
        .multicall(true)
        .subcommand(
            Command::new("busybox")
                .arg_required_else_help(true)
                .subcommand_value_name("APPLET")
                .subcommand_help_heading("APPLETS")
                .arg(
                    Arg::new("install")
                        .long("install")
                        .help("Install hardlinks for all subcommands in path")
                        .exclusive(true)
                        .takes_value(true)
                        .default_missing_value("/usr/local/bin")
                        .value_parser(value_parser!(PathBuf))
                        .use_value_delimiter(false),
                )
                .subcommands(applet_commands()),
        )
        .subcommands(applet_commands());

    let matches = cmd.get_matches();
    let mut subcommand = matches.subcommand();
    if let Some(("busybox", cmd)) = subcommand {
        if cmd.contains_id("install") {
            unimplemented!("Make hardlinks to the executable here");
        }
        subcommand = cmd.subcommand();
    }
    match subcommand {
        Some(("false", _)) => exit(1),
        Some(("true", _)) => exit(0),
        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    }
}

Sets the description of the argument for long help (--help).

Typically this a more detailed (multi-line) message that describes the arg.

If Arg::help is not specified, this message will be displayed for -h.

NOTE: Only Arg::help is used in completion script generation in order to be concise

Examples

Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to include a newline in the help text and have the following text be properly aligned with all the other help text.

Setting help displays a short message to the side of the argument when the user passes -h or --help (by default).

let m = Command::new("prog")
    .arg(Arg::new("cfg")
        .long("config")
        .long_help(
"The config file used by the myprog must be in JSON format
with only valid keys and may not contain other nonsense
that cannot be read by this program. Obviously I'm going on
and on, so I'll stop now."))
    .get_matches_from(vec![
        "prog", "--help"
    ]);

The above example displays

prog

USAGE:
    prog [OPTIONS]

OPTIONS:
        --config
            The config file used by the myprog must be in JSON format
            with only valid keys and may not contain other nonsense
            that cannot be read by this program. Obviously I'm going on
            and on, so I'll stop now.

    -h, --help
            Print help information

    -V, --version
            Print version information

Allows custom ordering of args within the help message.

Args with a lower value will be displayed first in the help message. This is helpful when one would like to emphasise frequently used args, or prioritize those towards the top of the list. Args with duplicate display orders will be displayed in alphabetical order.

NOTE: The default is 999 for all arguments.

NOTE: This setting is ignored for positional arguments which are always displayed in index order.

Examples
let m = Command::new("prog")
    .arg(Arg::new("a") // Typically args are grouped alphabetically by name.
                             // Args without a display_order have a value of 999 and are
                             // displayed alphabetically with all other 999 valued args.
        .long("long-option")
        .short('o')
        .takes_value(true)
        .help("Some help and text"))
    .arg(Arg::new("b")
        .long("other-option")
        .short('O')
        .takes_value(true)
        .display_order(1)   // In order to force this arg to appear *first*
                            // all we have to do is give it a value lower than 999.
                            // Any other args with a value of 1 will be displayed
                            // alphabetically with this one...then 2 values, then 3, etc.
        .help("I should be first!"))
    .get_matches_from(vec![
        "prog", "--help"
    ]);

The above example displays the following help message

cust-ord

USAGE:
    cust-ord [OPTIONS]

OPTIONS:
    -h, --help                Print help information
    -V, --version             Print version information
    -O, --other-option <b>    I should be first!
    -o, --long-option <a>     Some help and text

Override the current help section.

Render the help on the line after the argument.

This can be helpful for arguments with very long or complex help messages. This can also be helpful for arguments with very long flag names, or many/long value names.

NOTE: To apply this setting to all arguments and subcommands, consider using crate::Command::next_line_help

Examples
let m = Command::new("prog")
    .arg(Arg::new("opt")
        .long("long-option-flag")
        .short('o')
        .takes_value(true)
        .next_line_help(true)
        .value_names(&["value1", "value2"])
        .help("Some really long help and complex\n\
               help that makes more sense to be\n\
               on a line after the option"))
    .get_matches_from(vec![
        "prog", "--help"
    ]);

The above example displays the following help message

nlh

USAGE:
    nlh [OPTIONS]

OPTIONS:
    -h, --help       Print help information
    -V, --version    Print version information
    -o, --long-option-flag <value1> <value2>
        Some really long help and complex
        help that makes more sense to be
        on a line after the option

Do not display the argument in help message.

NOTE: This does not hide the argument from usage strings on error

Examples

Setting Hidden will hide the argument when displaying help text

let m = Command::new("prog")
    .arg(Arg::new("cfg")
        .long("config")
        .hide(true)
        .help("Some help text describing the --config arg"))
    .get_matches_from(vec![
        "prog", "--help"
    ]);

The above example displays

helptest

USAGE:
   helptest [OPTIONS]

OPTIONS:
-h, --help       Print help information
-V, --version    Print version information

Do not display the possible values in the help message.

This is useful for args with many values, or ones which are explained elsewhere in the help text.

NOTE: Setting this requires Arg::takes_value

To set this for all arguments, see Command::hide_possible_values.

Examples
let m = Command::new("prog")
    .arg(Arg::new("mode")
        .long("mode")
        .value_parser(["fast", "slow"])
        .takes_value(true)
        .hide_possible_values(true));

If we were to run the above program with --help the [values: fast, slow] portion of the help text would be omitted.

Do not display the default value of the argument in the help message.

This is useful when default behavior of an arg is explained elsewhere in the help text.

NOTE: Setting this requires Arg::takes_value

Examples
let m = Command::new("connect")
    .arg(Arg::new("host")
        .long("host")
        .default_value("localhost")
        .takes_value(true)
        .hide_default_value(true));

If we were to run the above program with --help the [default: localhost] portion of the help text would be omitted.

Available on crate feature env only.

Do not display in help the environment variable name.

This is useful when the variable option is explained elsewhere in the help text.

Examples
let m = Command::new("prog")
    .arg(Arg::new("mode")
        .long("mode")
        .env("MODE")
        .takes_value(true)
        .hide_env(true));

If we were to run the above program with --help the [env: MODE] portion of the help text would be omitted.

Available on crate feature env only.

Do not display in help any values inside the associated ENV variables for the argument.

This is useful when ENV vars contain sensitive values.

Examples
let m = Command::new("connect")
    .arg(Arg::new("host")
        .long("host")
        .env("CONNECT")
        .takes_value(true)
        .hide_env_values(true));

If we were to run the above program with $ CONNECT=super_secret connect --help the [default: CONNECT=super_secret] portion of the help text would be omitted.

Hides an argument from short help (-h).

NOTE: This does not hide the argument from usage strings on error

NOTE: Setting this option will cause next-line-help output style to be used when long help (--help) is called.

Examples
Arg::new("debug")
    .hide_short_help(true);

Setting hide_short_help(true) will hide the argument when displaying short help text

let m = Command::new("prog")
    .arg(Arg::new("cfg")
        .long("config")
        .hide_short_help(true)
        .help("Some help text describing the --config arg"))
    .get_matches_from(vec![
        "prog", "-h"
    ]);

The above example displays

helptest

USAGE:
   helptest [OPTIONS]

OPTIONS:
-h, --help       Print help information
-V, --version    Print version information

However, when –help is called

let m = Command::new("prog")
    .arg(Arg::new("cfg")
        .long("config")
        .hide_short_help(true)
        .help("Some help text describing the --config arg"))
    .get_matches_from(vec![
        "prog", "--help"
    ]);

Then the following would be displayed

helptest

USAGE:
   helptest [OPTIONS]

OPTIONS:
    --config     Some help text describing the --config arg
-h, --help       Print help information
-V, --version    Print version information

Hides an argument from long help (--help).

NOTE: This does not hide the argument from usage strings on error

NOTE: Setting this option will cause next-line-help output style to be used when long help (--help) is called.

Examples

Setting hide_long_help(true) will hide the argument when displaying long help text

let m = Command::new("prog")
    .arg(Arg::new("cfg")
        .long("config")
        .hide_long_help(true)
        .help("Some help text describing the --config arg"))
    .get_matches_from(vec![
        "prog", "--help"
    ]);

The above example displays

helptest

USAGE:
   helptest [OPTIONS]

OPTIONS:
-h, --help       Print help information
-V, --version    Print version information

However, when -h is called

let m = Command::new("prog")
    .arg(Arg::new("cfg")
        .long("config")
        .hide_long_help(true)
        .help("Some help text describing the --config arg"))
    .get_matches_from(vec![
        "prog", "-h"
    ]);

Then the following would be displayed

helptest

USAGE:
   helptest [OPTIONS]

OPTIONS:
    --config     Some help text describing the --config arg
-h, --help       Print help information
-V, --version    Print version information

The name of the ArgGroup the argument belongs to.

Examples
Arg::new("debug")
    .long("debug")
    .group("mode")

Multiple arguments can be a member of a single group and then the group checked as if it was one of said arguments.

let m = Command::new("prog")
    .arg(Arg::new("debug")
        .long("debug")
        .group("mode"))
    .arg(Arg::new("verbose")
        .long("verbose")
        .group("mode"))
    .get_matches_from(vec![
        "prog", "--debug"
    ]);
assert!(m.contains_id("mode"));
Examples found in repository?
examples/tutorial_builder/04_03_relations.rs (line 24)
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
fn main() {
    // Create application like normal
    let matches = command!() // requires `cargo` feature
        // Add the version arguments
        .arg(arg!(--"set-ver" <VER> "set version manually").required(false))
        .arg(arg!(--major         "auto inc major").action(ArgAction::SetTrue))
        .arg(arg!(--minor         "auto inc minor").action(ArgAction::SetTrue))
        .arg(arg!(--patch         "auto inc patch").action(ArgAction::SetTrue))
        // Create a group, make it required, and add the above arguments
        .group(
            ArgGroup::new("vers")
                .required(true)
                .args(&["set-ver", "major", "minor", "patch"]),
        )
        // Arguments can also be added to a group individually, these two arguments
        // are part of the "input" group which is not required
        .arg(
            arg!([INPUT_FILE] "some regular input")
                .value_parser(value_parser!(PathBuf))
                .group("input"),
        )
        .arg(
            arg!(--"spec-in" <SPEC_IN> "some special input argument")
                .required(false)
                .value_parser(value_parser!(PathBuf))
                .group("input"),
        )
        // Now let's assume we have a -c [config] argument which requires one of
        // (but **not** both) the "input" arguments
        .arg(
            arg!(config: -c <CONFIG>)
                .required(false)
                .value_parser(value_parser!(PathBuf))
                .requires("input"),
        )
        .get_matches();

    // Let's assume the old version 1.2.3
    let mut major = 1;
    let mut minor = 2;
    let mut patch = 3;

    // See if --set-ver was used to set the version manually
    let version = if let Some(ver) = matches.get_one::<String>("set-ver") {
        ver.to_owned()
    } else {
        // Increment the one requested (in a real program, we'd reset the lower numbers)
        let (maj, min, pat) = (
            matches.get_flag("major"),
            matches.get_flag("minor"),
            matches.get_flag("patch"),
        );
        match (maj, min, pat) {
            (true, _, _) => major += 1,
            (_, true, _) => minor += 1,
            (_, _, true) => patch += 1,
            _ => unreachable!(),
        };
        format!("{}.{}.{}", major, minor, patch)
    };

    println!("Version: {}", version);

    // Check for usage of -c
    if matches.contains_id("config") {
        let input = matches
            .get_one::<PathBuf>("INPUT_FILE")
            .unwrap_or_else(|| matches.get_one::<PathBuf>("spec-in").unwrap())
            .display();
        println!(
            "Doing work using input {} and config {}",
            input,
            matches.get_one::<PathBuf>("config").unwrap().display()
        );
    }
}

The names of ArgGroup’s the argument belongs to.

Examples
Arg::new("debug")
    .long("debug")
    .groups(&["mode", "verbosity"])

Arguments can be members of multiple groups and then the group checked as if it was one of said arguments.

let m = Command::new("prog")
    .arg(Arg::new("debug")
        .long("debug")
        .groups(&["mode", "verbosity"]))
    .arg(Arg::new("verbose")
        .long("verbose")
        .groups(&["mode", "verbosity"]))
    .get_matches_from(vec![
        "prog", "--debug"
    ]);
assert!(m.contains_id("mode"));
assert!(m.contains_id("verbosity"));

Specifies the value of the argument if arg has been used at runtime.

If val is set to None, arg only needs to be present. If val is set to "some-val" then arg must be present at runtime and have the value val.

If default is set to None, default_value will be removed.

NOTE: This setting is perfectly compatible with Arg::default_value but slightly different. Arg::default_value only takes effect when the user has not provided this arg at runtime. This setting however only takes effect when the user has not provided a value at runtime and these other conditions are met as well. If you have set Arg::default_value and Arg::default_value_if, and the user did not provide this arg at runtime, nor were the conditions met for Arg::default_value_if, the Arg::default_value will be applied.

NOTE: This implicitly sets Arg::takes_value(true).

Examples

First we use the default value only if another arg is present at runtime.

let m = Command::new("prog")
    .arg(Arg::new("flag")
        .long("flag"))
    .arg(Arg::new("other")
        .long("other")
        .default_value_if("flag", None, Some("default")))
    .get_matches_from(vec![
        "prog", "--flag"
    ]);

assert_eq!(m.value_of("other"), Some("default"));

Next we run the same test, but without providing --flag.

let m = Command::new("prog")
    .arg(Arg::new("flag")
        .long("flag"))
    .arg(Arg::new("other")
        .long("other")
        .default_value_if("flag", None, Some("default")))
    .get_matches_from(vec![
        "prog"
    ]);

assert_eq!(m.value_of("other"), None);

Now lets only use the default value if --opt contains the value special.

let m = Command::new("prog")
    .arg(Arg::new("opt")
        .takes_value(true)
        .long("opt"))
    .arg(Arg::new("other")
        .long("other")
        .default_value_if("opt", Some("special"), Some("default")))
    .get_matches_from(vec![
        "prog", "--opt", "special"
    ]);

assert_eq!(m.value_of("other"), Some("default"));

We can run the same test and provide any value other than special and we won’t get a default value.

let m = Command::new("prog")
    .arg(Arg::new("opt")
        .takes_value(true)
        .long("opt"))
    .arg(Arg::new("other")
        .long("other")
        .default_value_if("opt", Some("special"), Some("default")))
    .get_matches_from(vec![
        "prog", "--opt", "hahaha"
    ]);

assert_eq!(m.value_of("other"), None);

If we want to unset the default value for an Arg based on the presence or value of some other Arg.

let m = Command::new("prog")
    .arg(Arg::new("flag")
        .long("flag"))
    .arg(Arg::new("other")
        .long("other")
        .default_value("default")
        .default_value_if("flag", None, None))
    .get_matches_from(vec![
        "prog", "--flag"
    ]);

assert_eq!(m.value_of("other"), None);

Provides a conditional default value in the exact same manner as Arg::default_value_if only using OsStrs instead.

Specifies multiple values and conditions in the same manner as Arg::default_value_if.

The method takes a slice of tuples in the (arg, Option<val>, default) format.

NOTE: The conditions are stored in order and evaluated in the same order. I.e. the first if multiple conditions are true, the first one found will be applied and the ultimate value.

Examples

First we use the default value only if another arg is present at runtime.

let m = Command::new("prog")
    .arg(Arg::new("flag")
        .long("flag"))
    .arg(Arg::new("opt")
        .long("opt")
        .takes_value(true))
    .arg(Arg::new("other")
        .long("other")
        .default_value_ifs(&[
            ("flag", None, Some("default")),
            ("opt", Some("channal"), Some("chan")),
        ]))
    .get_matches_from(vec![
        "prog", "--opt", "channal"
    ]);

assert_eq!(m.value_of("other"), Some("chan"));

Next we run the same test, but without providing --flag.

let m = Command::new("prog")
    .arg(Arg::new("flag")
        .long("flag"))
    .arg(Arg::new("other")
        .long("other")
        .default_value_ifs(&[
            ("flag", None, Some("default")),
            ("opt", Some("channal"), Some("chan")),
        ]))
    .get_matches_from(vec![
        "prog"
    ]);

assert_eq!(m.value_of("other"), None);

We can also see that these values are applied in order, and if more than one condition is true, only the first evaluated “wins”

let m = Command::new("prog")
    .arg(Arg::new("flag")
        .long("flag"))
    .arg(Arg::new("opt")
        .long("opt")
        .takes_value(true))
    .arg(Arg::new("other")
        .long("other")
        .default_value_ifs(&[
            ("flag", None, Some("default")),
            ("opt", Some("channal"), Some("chan")),
        ]))
    .get_matches_from(vec![
        "prog", "--opt", "channal", "--flag"
    ]);

assert_eq!(m.value_of("other"), Some("default"));

Provides multiple conditional default values in the exact same manner as Arg::default_value_ifs only using OsStrs instead.

Set this arg as required as long as the specified argument is not present at runtime.

Pro Tip: Using Arg::required_unless_present implies Arg::required and is therefore not mandatory to also set.

Examples
Arg::new("config")
    .required_unless_present("debug")

In the following example, the required argument is not provided, but it’s not an error because the unless arg has been supplied.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .required_unless_present("dbg")
        .takes_value(true)
        .long("config"))
    .arg(Arg::new("dbg")
        .long("debug"))
    .try_get_matches_from(vec![
        "prog", "--debug"
    ]);

assert!(res.is_ok());

Setting Arg::required_unless_present(name) and not supplying name or this arg is an error.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .required_unless_present("dbg")
        .takes_value(true)
        .long("config"))
    .arg(Arg::new("dbg")
        .long("debug"))
    .try_get_matches_from(vec![
        "prog"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
Examples found in repository?
examples/pacman.rs (line 65)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
fn main() {
    let matches = Command::new("pacman")
        .about("package manager utility")
        .version("5.2.1")
        .subcommand_required(true)
        .arg_required_else_help(true)
        .author("Pacman Development Team")
        // Query subcommand
        //
        // Only a few of its arguments are implemented below.
        .subcommand(
            Command::new("query")
                .short_flag('Q')
                .long_flag("query")
                .about("Query the package database.")
                .arg(
                    Arg::new("search")
                        .short('s')
                        .long("search")
                        .help("search locally installed packages for matching strings")
                        .conflicts_with("info")
                        .takes_value(true)
                        .multiple_values(true),
                )
                .arg(
                    Arg::new("info")
                        .long("info")
                        .short('i')
                        .conflicts_with("search")
                        .help("view package information")
                        .takes_value(true)
                        .multiple_values(true),
                ),
        )
        // Sync subcommand
        //
        // Only a few of its arguments are implemented below.
        .subcommand(
            Command::new("sync")
                .short_flag('S')
                .long_flag("sync")
                .about("Synchronize packages.")
                .arg(
                    Arg::new("search")
                        .short('s')
                        .long("search")
                        .conflicts_with("info")
                        .takes_value(true)
                        .multiple_values(true)
                        .help("search remote repositories for matching strings"),
                )
                .arg(
                    Arg::new("info")
                        .long("info")
                        .conflicts_with("search")
                        .short('i')
                        .action(ArgAction::SetTrue)
                        .help("view package information"),
                )
                .arg(
                    Arg::new("package")
                        .help("packages")
                        .required_unless_present("search")
                        .takes_value(true)
                        .multiple_values(true),
                ),
        )
        .get_matches();

    match matches.subcommand() {
        Some(("sync", sync_matches)) => {
            if sync_matches.contains_id("search") {
                let packages: Vec<_> = sync_matches
                    .get_many::<String>("search")
                    .expect("contains_id")
                    .map(|s| s.as_str())
                    .collect();
                let values = packages.join(", ");
                println!("Searching for {}...", values);
                return;
            }

            let packages: Vec<_> = sync_matches
                .get_many::<String>("package")
                .expect("is present")
                .map(|s| s.as_str())
                .collect();
            let values = packages.join(", ");

            if sync_matches.get_flag("info") {
                println!("Retrieving info for {}...", values);
            } else {
                println!("Installing {}...", values);
            }
        }
        Some(("query", query_matches)) => {
            if let Some(packages) = query_matches.get_many::<String>("info") {
                let comma_sep = packages.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
                println!("Retrieving info for {}...", comma_sep);
            } else if let Some(queries) = query_matches.get_many::<String>("search") {
                let comma_sep = queries.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
                println!("Searching Locally for {}...", comma_sep);
            } else {
                println!("Displaying all locally installed packages...");
            }
        }
        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
    }
}

Sets this arg as required unless all of the specified arguments are present at runtime.

In other words, parsing will succeed only if user either

  • supplies the self arg.
  • supplies all of the names arguments.

NOTE: If you wish for this argument to only be required unless any of these args are present see Arg::required_unless_present_any

Examples
Arg::new("config")
    .required_unless_present_all(&["cfg", "dbg"])

In the following example, the required argument is not provided, but it’s not an error because all of the names args have been supplied.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .required_unless_present_all(&["dbg", "infile"])
        .takes_value(true)
        .long("config"))
    .arg(Arg::new("dbg")
        .long("debug"))
    .arg(Arg::new("infile")
        .short('i')
        .takes_value(true))
    .try_get_matches_from(vec![
        "prog", "--debug", "-i", "file"
    ]);

assert!(res.is_ok());

Setting Arg::required_unless_present_all(names) and not supplying either all of unless args or the self arg is an error.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .required_unless_present_all(&["dbg", "infile"])
        .takes_value(true)
        .long("config"))
    .arg(Arg::new("dbg")
        .long("debug"))
    .arg(Arg::new("infile")
        .short('i')
        .takes_value(true))
    .try_get_matches_from(vec![
        "prog"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);

Sets this arg as required unless any of the specified arguments are present at runtime.

In other words, parsing will succeed only if user either

  • supplies the self arg.
  • supplies one or more of the unless arguments.

NOTE: If you wish for this argument to be required unless all of these args are present see Arg::required_unless_present_all

Examples
Arg::new("config")
    .required_unless_present_any(&["cfg", "dbg"])

Setting Arg::required_unless_present_any(names) requires that the argument be used at runtime unless at least one of the args in names are present. In the following example, the required argument is not provided, but it’s not an error because one the unless args have been supplied.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .required_unless_present_any(&["dbg", "infile"])
        .takes_value(true)
        .long("config"))
    .arg(Arg::new("dbg")
        .long("debug"))
    .arg(Arg::new("infile")
        .short('i')
        .takes_value(true))
    .try_get_matches_from(vec![
        "prog", "--debug"
    ]);

assert!(res.is_ok());

Setting Arg::required_unless_present_any(names) and not supplying at least one of names or this arg is an error.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .required_unless_present_any(&["dbg", "infile"])
        .takes_value(true)
        .long("config"))
    .arg(Arg::new("dbg")
        .long("debug"))
    .arg(Arg::new("infile")
        .short('i')
        .takes_value(true))
    .try_get_matches_from(vec![
        "prog"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);

This argument is required only if the specified arg is present at runtime and its value equals val.

Examples
Arg::new("config")
    .required_if_eq("other_arg", "value")
let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .takes_value(true)
        .required_if_eq("other", "special")
        .long("config"))
    .arg(Arg::new("other")
        .long("other")
        .takes_value(true))
    .try_get_matches_from(vec![
        "prog", "--other", "not-special"
    ]);

assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .takes_value(true)
        .required_if_eq("other", "special")
        .long("config"))
    .arg(Arg::new("other")
        .long("other")
        .takes_value(true))
    .try_get_matches_from(vec![
        "prog", "--other", "special"
    ]);

// We did use --other=special so "cfg" had become required but was missing.
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .takes_value(true)
        .required_if_eq("other", "special")
        .long("config"))
    .arg(Arg::new("other")
        .long("other")
        .takes_value(true))
    .try_get_matches_from(vec![
        "prog", "--other", "SPECIAL"
    ]);

// By default, the comparison is case-sensitive, so "cfg" wasn't required
assert!(res.is_ok());

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .takes_value(true)
        .required_if_eq("other", "special")
        .long("config"))
    .arg(Arg::new("other")
        .long("other")
        .ignore_case(true)
        .takes_value(true))
    .try_get_matches_from(vec![
        "prog", "--other", "SPECIAL"
    ]);

// However, case-insensitive comparisons can be enabled.  This typically occurs when using Arg::possible_values().
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);

Specify this argument is required based on multiple conditions.

The conditions are set up in a (arg, val) style tuple. The requirement will only become valid if one of the specified arg’s value equals its corresponding val.

Examples
Arg::new("config")
    .required_if_eq_any(&[
        ("extra", "val"),
        ("option", "spec")
    ])

Setting Arg::required_if_eq_any(&[(arg, val)]) makes this arg required if any of the args are used at runtime and it’s corresponding value is equal to val. If the arg’s value is anything other than val, this argument isn’t required.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .required_if_eq_any(&[
            ("extra", "val"),
            ("option", "spec")
        ])
        .takes_value(true)
        .long("config"))
    .arg(Arg::new("extra")
        .takes_value(true)
        .long("extra"))
    .arg(Arg::new("option")
        .takes_value(true)
        .long("option"))
    .try_get_matches_from(vec![
        "prog", "--option", "other"
    ]);

assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required

Setting Arg::required_if_eq_any(&[(arg, val)]) and having any of the args used with its value of val but not using this arg is an error.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .required_if_eq_any(&[
            ("extra", "val"),
            ("option", "spec")
        ])
        .takes_value(true)
        .long("config"))
    .arg(Arg::new("extra")
        .takes_value(true)
        .long("extra"))
    .arg(Arg::new("option")
        .takes_value(true)
        .long("option"))
    .try_get_matches_from(vec![
        "prog", "--option", "spec"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);

Specify this argument is required based on multiple conditions.

The conditions are set up in a (arg, val) style tuple. The requirement will only become valid if every one of the specified arg’s value equals its corresponding val.

Examples
Arg::new("config")
    .required_if_eq_all(&[
        ("extra", "val"),
        ("option", "spec")
    ])

Setting Arg::required_if_eq_all(&[(arg, val)]) makes this arg required if all of the args are used at runtime and every value is equal to its corresponding val. If the arg’s value is anything other than val, this argument isn’t required.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .required_if_eq_all(&[
            ("extra", "val"),
            ("option", "spec")
        ])
        .takes_value(true)
        .long("config"))
    .arg(Arg::new("extra")
        .takes_value(true)
        .long("extra"))
    .arg(Arg::new("option")
        .takes_value(true)
        .long("option"))
    .try_get_matches_from(vec![
        "prog", "--option", "spec"
    ]);

assert!(res.is_ok()); // We didn't use --option=spec --extra=val so "cfg" isn't required

Setting Arg::required_if_eq_all(&[(arg, val)]) and having all of the args used with its value of val but not using this arg is an error.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .required_if_eq_all(&[
            ("extra", "val"),
            ("option", "spec")
        ])
        .takes_value(true)
        .long("config"))
    .arg(Arg::new("extra")
        .takes_value(true)
        .long("extra"))
    .arg(Arg::new("option")
        .takes_value(true)
        .long("option"))
    .try_get_matches_from(vec![
        "prog", "--extra", "val", "--option", "spec"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);

Require another argument if this arg was present at runtime and its value equals to val.

This method takes value, another_arg pair. At runtime, clap will check if this arg (self) is present and its value equals to val. If it does, another_arg will be marked as required.

Examples
Arg::new("config")
    .requires_if("val", "arg")

Setting Arg::requires_if(val, arg) requires that the arg be used at runtime if the defining argument’s value is equal to val. If the defining argument is anything other than val, the other argument isn’t required.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .takes_value(true)
        .requires_if("my.cfg", "other")
        .long("config"))
    .arg(Arg::new("other"))
    .try_get_matches_from(vec![
        "prog", "--config", "some.cfg"
    ]);

assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required

Setting Arg::requires_if(val, arg) and setting the value to val but not supplying arg is an error.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .takes_value(true)
        .requires_if("my.cfg", "input")
        .long("config"))
    .arg(Arg::new("input"))
    .try_get_matches_from(vec![
        "prog", "--config", "my.cfg"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);

Allows multiple conditional requirements.

The requirement will only become valid if this arg’s value equals val.

Examples
Arg::new("config")
    .requires_ifs(&[
        ("val", "arg"),
        ("other_val", "arg2"),
    ])

Setting Arg::requires_ifs(&["val", "arg"]) requires that the arg be used at runtime if the defining argument’s value is equal to val. If the defining argument’s value is anything other than val, arg isn’t required.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .takes_value(true)
        .requires_ifs(&[
            ("special.conf", "opt"),
            ("other.conf", "other"),
        ])
        .long("config"))
    .arg(Arg::new("opt")
        .long("option")
        .takes_value(true))
    .arg(Arg::new("other"))
    .try_get_matches_from(vec![
        "prog", "--config", "special.conf"
    ]);

assert!(res.is_err()); // We  used --config=special.conf so --option <val> is required
assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);

Require these arguments names when this one is presen

i.e. when using this argument, the following arguments must be present.

NOTE: Conflicting rules and override rules take precedence over being required by default.

Examples
Arg::new("config")
    .requires_all(&["input", "output"])

Setting Arg::requires_all(&[arg, arg2]) requires that all the arguments be used at runtime if the defining argument is used. If the defining argument isn’t used, the other argument isn’t required

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .takes_value(true)
        .requires("input")
        .long("config"))
    .arg(Arg::new("input"))
    .arg(Arg::new("output"))
    .try_get_matches_from(vec![
        "prog"
    ]);

assert!(res.is_ok()); // We didn't use cfg, so input and output weren't required

Setting Arg::requires_all(&[arg, arg2]) and not supplying all the arguments is an error.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .takes_value(true)
        .requires_all(&["input", "output"])
        .long("config"))
    .arg(Arg::new("input"))
    .arg(Arg::new("output"))
    .try_get_matches_from(vec![
        "prog", "--config", "file.conf", "in.txt"
    ]);

assert!(res.is_err());
// We didn't use output
assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);

This argument is mutually exclusive with the specified argument.

NOTE: Conflicting rules take precedence over being required by default. Conflict rules only need to be set for one of the two arguments, they do not need to be set for each.

NOTE: Defining a conflict is two-way, but does not need to defined for both arguments (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need to also do B.conflicts_with(A))

NOTE: Arg::conflicts_with_all(names) allows specifying an argument which conflicts with more than one argument.

NOTE Arg::exclusive(true) allows specifying an argument which conflicts with every other argument.

Examples
Arg::new("config")
    .conflicts_with("debug")

Setting conflicting argument, and having both arguments present at runtime is an error.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .takes_value(true)
        .conflicts_with("debug")
        .long("config"))
    .arg(Arg::new("debug")
        .long("debug"))
    .try_get_matches_from(vec![
        "prog", "--debug", "--config", "file.conf"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
Examples found in repository?
examples/pacman.rs (line 23)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
fn main() {
    let matches = Command::new("pacman")
        .about("package manager utility")
        .version("5.2.1")
        .subcommand_required(true)
        .arg_required_else_help(true)
        .author("Pacman Development Team")
        // Query subcommand
        //
        // Only a few of its arguments are implemented below.
        .subcommand(
            Command::new("query")
                .short_flag('Q')
                .long_flag("query")
                .about("Query the package database.")
                .arg(
                    Arg::new("search")
                        .short('s')
                        .long("search")
                        .help("search locally installed packages for matching strings")
                        .conflicts_with("info")
                        .takes_value(true)
                        .multiple_values(true),
                )
                .arg(
                    Arg::new("info")
                        .long("info")
                        .short('i')
                        .conflicts_with("search")
                        .help("view package information")
                        .takes_value(true)
                        .multiple_values(true),
                ),
        )
        // Sync subcommand
        //
        // Only a few of its arguments are implemented below.
        .subcommand(
            Command::new("sync")
                .short_flag('S')
                .long_flag("sync")
                .about("Synchronize packages.")
                .arg(
                    Arg::new("search")
                        .short('s')
                        .long("search")
                        .conflicts_with("info")
                        .takes_value(true)
                        .multiple_values(true)
                        .help("search remote repositories for matching strings"),
                )
                .arg(
                    Arg::new("info")
                        .long("info")
                        .conflicts_with("search")
                        .short('i')
                        .action(ArgAction::SetTrue)
                        .help("view package information"),
                )
                .arg(
                    Arg::new("package")
                        .help("packages")
                        .required_unless_present("search")
                        .takes_value(true)
                        .multiple_values(true),
                ),
        )
        .get_matches();

    match matches.subcommand() {
        Some(("sync", sync_matches)) => {
            if sync_matches.contains_id("search") {
                let packages: Vec<_> = sync_matches
                    .get_many::<String>("search")
                    .expect("contains_id")
                    .map(|s| s.as_str())
                    .collect();
                let values = packages.join(", ");
                println!("Searching for {}...", values);
                return;
            }

            let packages: Vec<_> = sync_matches
                .get_many::<String>("package")
                .expect("is present")
                .map(|s| s.as_str())
                .collect();
            let values = packages.join(", ");

            if sync_matches.get_flag("info") {
                println!("Retrieving info for {}...", values);
            } else {
                println!("Installing {}...", values);
            }
        }
        Some(("query", query_matches)) => {
            if let Some(packages) = query_matches.get_many::<String>("info") {
                let comma_sep = packages.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
                println!("Retrieving info for {}...", comma_sep);
            } else if let Some(queries) = query_matches.get_many::<String>("search") {
                let comma_sep = queries.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
                println!("Searching Locally for {}...", comma_sep);
            } else {
                println!("Displaying all locally installed packages...");
            }
        }
        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
    }
}

This argument is mutually exclusive with the specified arguments.

See Arg::conflicts_with.

NOTE: Conflicting rules take precedence over being required by default. Conflict rules only need to be set for one of the two arguments, they do not need to be set for each.

NOTE: Defining a conflict is two-way, but does not need to defined for both arguments (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need need to also do B.conflicts_with(A))

NOTE: Arg::exclusive(true) allows specifying an argument which conflicts with every other argument.

Examples
Arg::new("config")
    .conflicts_with_all(&["debug", "input"])

Setting conflicting argument, and having any of the arguments present at runtime with a conflicting argument is an error.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .takes_value(true)
        .conflicts_with_all(&["debug", "input"])
        .long("config"))
    .arg(Arg::new("debug")
        .long("debug"))
    .arg(Arg::new("input"))
    .try_get_matches_from(vec![
        "prog", "--config", "file.conf", "file.txt"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);

Sets an overridable argument.

i.e. this argument and the following argument will override each other in POSIX style (whichever argument was specified at runtime last “wins”)

NOTE: When an argument is overridden it is essentially as if it never was used, any conflicts, requirements, etc. are evaluated after all “overrides” have been removed

NOTE: Overriding an argument implies they conflict.

WARNING: Positional arguments and options which accept Arg::multiple_occurrences cannot override themselves (or we would never be able to advance to the next positional). If a positional argument or option with one of the Arg::multiple_occurrences settings lists itself as an override, it is simply ignored.

Examples
let m = Command::new("prog")
    .arg(arg!(-f --flag "some flag")
        .conflicts_with("debug"))
    .arg(arg!(-d --debug "other flag"))
    .arg(arg!(-c --color "third flag")
        .overrides_with("flag"))
    .get_matches_from(vec![
        "prog", "-f", "-d", "-c"]);
            //    ^~~~~~~~~~~~^~~~~ flag is overridden by color

assert!(m.is_present("color"));
assert!(m.is_present("debug")); // even though flag conflicts with debug, it's as if flag
                                // was never used because it was overridden with color
assert!(!m.is_present("flag"));

Care must be taken when using this setting, and having an arg override with itself. This is common practice when supporting things like shell aliases, config files, etc. However, when combined with multiple values, it can get dicy. Here is how clap handles such situations:

When a flag overrides itself, it’s as if the flag was only ever used once (essentially preventing a “Unexpected multiple usage” error):

let m = Command::new("posix")
            .arg(arg!(--flag  "some flag").overrides_with("flag"))
            .get_matches_from(vec!["posix", "--flag", "--flag"]);
assert!(m.is_present("flag"));

Making an arg Arg::multiple_occurrences and override itself is essentially meaningless. Therefore clap ignores an override of self if it’s a flag and it already accepts multiple occurrences.

let m = Command::new("posix")
            .arg(arg!(--flag ...  "some flag").overrides_with("flag"))
            .get_matches_from(vec!["", "--flag", "--flag", "--flag", "--flag"]);
assert!(m.is_present("flag"));

Now notice with options (which do not set Arg::multiple_occurrences), it’s as if only the last occurrence happened.

let m = Command::new("posix")
            .arg(arg!(--opt <val> "some option").overrides_with("opt"))
            .get_matches_from(vec!["", "--opt=some", "--opt=other"]);
assert!(m.is_present("opt"));
assert_eq!(m.value_of("opt"), Some("other"));

This will also work when Arg::multiple_values is enabled:

let m = Command::new("posix")
            .arg(
                Arg::new("opt")
                    .long("opt")
                    .takes_value(true)
                    .multiple_values(true)
                    .overrides_with("opt")
            )
            .get_matches_from(vec!["", "--opt", "1", "2", "--opt", "3", "4", "5"]);
assert!(m.is_present("opt"));
assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["3", "4", "5"]);

Just like flags, options with Arg::multiple_occurrences set will ignore the “override self” setting.

let m = Command::new("posix")
            .arg(arg!(--opt <val> ... "some option")
                .multiple_values(true)
                .overrides_with("opt"))
            .get_matches_from(vec!["", "--opt", "first", "over", "--opt", "other", "val"]);
assert!(m.is_present("opt"));
assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["first", "over", "other", "val"]);

Sets multiple mutually overridable arguments by name.

i.e. this argument and the following argument will override each other in POSIX style (whichever argument was specified at runtime last “wins”)

NOTE: When an argument is overridden it is essentially as if it never was used, any conflicts, requirements, etc. are evaluated after all “overrides” have been removed

NOTE: Overriding an argument implies they conflict.

Examples
let m = Command::new("prog")
    .arg(arg!(-f --flag "some flag")
        .conflicts_with("color"))
    .arg(arg!(-d --debug "other flag"))
    .arg(arg!(-c --color "third flag")
        .overrides_with_all(&["flag", "debug"]))
    .get_matches_from(vec![
        "prog", "-f", "-d", "-c"]);
            //    ^~~~~~^~~~~~~~~ flag and debug are overridden by color

assert!(m.is_present("color")); // even though flag conflicts with color, it's as if flag
                                // and debug were never used because they were overridden
                                // with color
assert!(!m.is_present("debug"));
assert!(!m.is_present("flag"));

Get the name of the argument

Deprecated, replaced with Arg::get_id

Get the help specified for this argument, if any

Get the long help specified for this argument, if any

Examples
let arg = Arg::new("foo").long_help("long help");
assert_eq!(Some("long help"), arg.get_long_help());

Get the help heading specified for this argument, if any

Get the short option name for this argument, if any

Get visible short aliases for this argument, if any

Get all short aliases for this argument, if any, both visible and hidden.

Get the short option name and its visible aliases, if any

Get the long option name for this argument, if any

Get visible aliases for this argument, if any

Get all aliases for this argument, if any, both visible and hidden.

Get the long option name and its visible aliases, if any

Deprecated, replaced with [Arg::get_value_parser().possible_values()]

Get the names of values for this argument.

Get the number of values for this argument.

Get the delimiter between multiple values

Get the index of this argument, if any

Get the value hint of this argument

Deprecated, replaced with Arg::is_global_set

Available on crate feature env only.

Get the environment variable name specified for this argument, if any

Examples
let arg = Arg::new("foo").env("ENVIRONMENT");
assert_eq!(Some(OsStr::new("ENVIRONMENT")), arg.get_env());

Get the default values specified for this argument, if any

Examples
let arg = Arg::new("foo").default_value("default value");
assert_eq!(&["default value"], arg.get_default_values());

Checks whether this argument is a positional or not.

Examples
let arg = Arg::new("foo");
assert_eq!(true, arg.is_positional());

let arg = Arg::new("foo").long("foo");
assert_eq!(false, arg.is_positional());

Reports whether Arg::required is set

Report whether Arg::multiple_values is set

Report whether Arg::is_takes_value_set is set

Report whether Arg::allow_hyphen_values is set

Deprecated, replaced with Arg::get_value_parser()

Deprecated, replaced with [Arg::get_value_parser()

Behavior when parsing the argument

Configured parser for argument values

Example
let cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("port")
            .value_parser(clap::value_parser!(usize))
    );
let value_parser = cmd.get_arguments()
    .find(|a| a.get_id() == "port").unwrap()
    .get_value_parser();
println!("{:?}", value_parser);

Report whether Arg::global is set

Report whether Arg::next_line_help is set

Report whether Arg::hide is set

Report whether Arg::hide_default_value is set

Report whether Arg::hide_possible_values is set

Available on crate feature env only.

Report whether Arg::hide_env is set

Available on crate feature env only.

Report whether Arg::hide_env_values is set

Report whether Arg::hide_short_help is set

Report whether Arg::hide_long_help is set

Report whether Arg::use_value_delimiter is set

Report whether Arg::require_value_delimiter is set

Report whether Arg::require_equals is set

Reports whether Arg::exclusive is set

Reports whether Arg::last is set

Reports whether Arg::ignore_case is set

This impl block contains no items.

Trait Implementations

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more
Formats the value using the given formatter. Read more
Converts to this type from the input type.
This method returns an Ordering between self and other. Read more
Compares and returns the maximum of two values. Read more
Compares and returns the minimum of two values. Read more
Restrict a value to a certain interval. Read more
This method tests for self and other values to be equal, and is used by ==. Read more
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more
This method returns an ordering between self and other values if one exists. Read more
This method tests less than (for self and other) and is used by the < operator. Read more
This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
This method tests greater than (for self and other) and is used by the > operator. Read more
This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Compare self to key and return true if they are equal.

Returns the argument unchanged.

Calls U::from(self).

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

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.