Skip to main content

## ArgMatches

# Struct ArgMatches

Source

    pub struct ArgMatches { /* private fields */ }

Expand description

Container for parse results.

Used to get information about the arguments that were supplied to the program at runtime by the user. New instances of this struct are obtained by using the `Command::get_matches` family of methods.

## §Examples

    let matches = Command::new("MyApp")
        .arg(Arg::new("out")
            .long("output")
            .required(true)
            .action(ArgAction::Set)
            .default_value("-"))
        .arg(Arg::new("cfg")
            .short('c')
            .action(ArgAction::Set))
        .get_matches(); // builds the instance of ArgMatches

    // to get information about the "cfg" argument we created, such as the value supplied we use
    // various ArgMatches methods, such as [ArgMatches::get_one]
    if let Some(c) = matches.get_one::<String>("cfg") {
        println!("Value for -c: {c}");
    }

    // The ArgMatches::get_one method returns an Option because the user may not have supplied
    // that argument at runtime. But if we specified that the argument was "required" as we did
    // with the "out" argument, we can safely unwrap because `clap` verifies that was actually
    // used at runtime.
    println!("Value for --output: {}", matches.get_one::<String>("out").unwrap());

    // You can check the presence of an argument's values
    if matches.contains_id("out") {
        // However, if you want to know where the value came from
        if matches.value_source("out").expect("checked contains_id") == ValueSource::CommandLine {
            println!("`out` set by user");
        } else {
            println!("`out` is defaulted");
        }
    }

## Implementations§

Source§

### impl ArgMatches

#### §Arguments

Source

#### pub fn get_one<T>(&self, id: &str) -> Option<&T>
where T: Any + Clone + Send + Sync + 'static,

Gets the value of a specific option or positional argument.

i.e. an argument that takes an additional value at runtime.

Returns an error if the wrong type was used.

Returns `None` if the option wasn’t present.

NOTE: This will always return `Some(value)` if `default_value` has been set. `ArgMatches::value_source` can be used to check if a value is present at runtime.

##### §Panic

If the argument definition and access mismatch. To handle this case programmatically, see `ArgMatches::try_get_one`.

##### §Examples

    let m = Command::new("myapp")
        .arg(Arg::new("port")
            .value_parser(value_parser!(usize))
            .action(ArgAction::Set)
            .required(true))
        .get_matches_from(vec!["myapp", "2020"]);

    let port: usize = *m
        .get_one("port")
        .expect("`port`is required");
    assert_eq!(port, 2020);

##### Examples found in repository?

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

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

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

    60fn main() {
    61    let matches = cli().get_matches();
    62
    63    match matches.subcommand() {
    64        Some(("clone", sub_matches)) => {
    65            println!(
    66                "Cloning {}",
    67                sub_matches.get_one::<String>("REMOTE").expect("required")
    68            );
    69        }
    70        Some(("diff", sub_matches)) => {
    71            let color = sub_matches
    72                .get_one::<String>("color")
    73                .map(|s| s.as_str())
    74                .expect("defaulted in clap");
    75
    76            let mut base = sub_matches.get_one::<String>("base").map(|s| s.as_str());
    77            let mut head = sub_matches.get_one::<String>("head").map(|s| s.as_str());
    78            let mut path = sub_matches.get_one::<String>("path").map(|s| s.as_str());
    79            if path.is_none() {
    80                path = head;
    81                head = None;
    82                if path.is_none() {
    83                    path = base;
    84                    base = None;
    85                }
    86            }
    87            let base = base.unwrap_or("stage");
    88            let head = head.unwrap_or("worktree");
    89            let path = path.unwrap_or("");
    90            println!("Diffing {base}..{head} {path} (color={color})");
    91        }
    92        Some(("push", sub_matches)) => {
    93            println!(
    94                "Pushing to {}",
    95                sub_matches.get_one::<String>("REMOTE").expect("required")
    96            );
    97        }
    98        Some(("add", sub_matches)) => {
    99            let paths = sub_matches
    100                .get_many::<PathBuf>("PATH")
    101                .into_iter()
    102                .flatten()
    103                .collect::<Vec<_>>();
    104            println!("Adding {paths:?}");
    105        }
    106        Some(("stash", sub_matches)) => {
    107            let stash_command = sub_matches.subcommand().unwrap_or(("push", sub_matches));
    108            match stash_command {
    109                ("apply", sub_matches) => {
    110                    let stash = sub_matches.get_one::<String>("STASH");
    111                    println!("Applying {stash:?}");
    112                }
    113                ("pop", sub_matches) => {
    114                    let stash = sub_matches.get_one::<String>("STASH");
    115                    println!("Popping {stash:?}");
    116                }
    117                ("push", sub_matches) => {
    118                    let message = sub_matches.get_one::<String>("message");
    119                    println!("Pushing {message:?}");
    120                }
    121                (name, _) => {
    122                    unreachable!("Unsupported subcommand `{name}`")
    123                }
    124            }
    125        }
    126        Some((ext, sub_matches)) => {
    127            let args = sub_matches
    128                .get_many::<OsString>("")
    129                .into_iter()
    130                .flatten()
    131                .collect::<Vec<_>>();
    132            println!("Calling out to {ext:?} with {args:?}");
    133        }
    134        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable!()
    135    }
    136
    137    // Continued program logic goes here...
    138}

Source

#### pub fn get_count(&self, id: &str) -> u8

Gets the value of a specific `ArgAction::Count` flag

##### §Panic

If the argument’s action is not `ArgAction::Count`

##### §Examples

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

    let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap();
    assert_eq!(
        matches.get_count("flag"),
        2
    );

Source

#### pub fn get_flag(&self, id: &str) -> bool

Gets the value of a specific `ArgAction::SetTrue` or `ArgAction::SetFalse` flag

##### §Panic

If the argument’s action is not `ArgAction::SetTrue` or `ArgAction::SetFalse`

##### §Examples

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

    let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap();
    assert!(matches.contains_id("flag"));
    assert_eq!(
        matches.get_flag("flag"),
        true
    );

##### Examples found in repository?

examples/derive_ref/flatten_hand_args.rs (line 18)

    16    fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result<Self, Error> {
    17        Ok(Self {
    18            foo: matches.get_flag("foo"),
    19            bar: matches.get_flag("bar"),
    20            quuz: matches.remove_one::<String>("quuz"),
    21        })
    22    }
    23    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
    24        let mut matches = matches.clone();
    25        self.update_from_arg_matches_mut(&mut matches)
    26    }
    27    fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> {
    28        self.foo |= matches.get_flag("foo");
    29        self.bar |= matches.get_flag("bar");
    30        if let Some(quuz) = matches.remove_one::<String>("quuz") {
    31            self.quuz = Some(quuz);
    32        }
    33        Ok(())
    34    }

More examples
Hide additional examples
examples/derive_ref/augment_args.rs (line 15)

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

examples/pacman.rs (line 94)

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

Source

#### pub fn get_many<T>(&self, id: &str) -> Option<ValuesRef<'_, T>>
where T: Any + Clone + Send + Sync + 'static,

Iterate over values of a specific option or positional argument.

i.e. an argument that takes multiple values at runtime.

Returns an error if the wrong type was used.

Returns `None` if the option wasn’t present.

##### §Panic

If the argument definition and access mismatch. To handle this case programmatically, see `ArgMatches::try_get_many`.

##### §Examples

    let m = Command::new("myprog")
        .arg(Arg::new("ports")
            .action(ArgAction::Append)
            .value_parser(value_parser!(usize))
            .short('p')
            .required(true))
        .get_matches_from(vec![
            "myprog", "-p", "22", "-p", "80", "-p", "2020"
        ]);
    let vals: Vec<usize> = m.get_many("ports")
        .expect("`port`is required")
        .copied()
        .collect();
    assert_eq!(vals, [22, 80, 2020]);

##### Examples found in repository?

examples/pacman.rs (line 78)

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

More examples
Hide additional examples
examples/git.rs (line 100)

    60fn main() {
    61    let matches = cli().get_matches();
    62
    63    match matches.subcommand() {
    64        Some(("clone", sub_matches)) => {
    65            println!(
    66                "Cloning {}",
    67                sub_matches.get_one::<String>("REMOTE").expect("required")
    68            );
    69        }
    70        Some(("diff", sub_matches)) => {
    71            let color = sub_matches
    72                .get_one::<String>("color")
    73                .map(|s| s.as_str())
    74                .expect("defaulted in clap");
    75
    76            let mut base = sub_matches.get_one::<String>("base").map(|s| s.as_str());
    77            let mut head = sub_matches.get_one::<String>("head").map(|s| s.as_str());
    78            let mut path = sub_matches.get_one::<String>("path").map(|s| s.as_str());
    79            if path.is_none() {
    80                path = head;
    81                head = None;
    82                if path.is_none() {
    83                    path = base;
    84                    base = None;
    85                }
    86            }
    87            let base = base.unwrap_or("stage");
    88            let head = head.unwrap_or("worktree");
    89            let path = path.unwrap_or("");
    90            println!("Diffing {base}..{head} {path} (color={color})");
    91        }
    92        Some(("push", sub_matches)) => {
    93            println!(
    94                "Pushing to {}",
    95                sub_matches.get_one::<String>("REMOTE").expect("required")
    96            );
    97        }
    98        Some(("add", sub_matches)) => {
    99            let paths = sub_matches
    100                .get_many::<PathBuf>("PATH")
    101                .into_iter()
    102                .flatten()
    103                .collect::<Vec<_>>();
    104            println!("Adding {paths:?}");
    105        }
    106        Some(("stash", sub_matches)) => {
    107            let stash_command = sub_matches.subcommand().unwrap_or(("push", sub_matches));
    108            match stash_command {
    109                ("apply", sub_matches) => {
    110                    let stash = sub_matches.get_one::<String>("STASH");
    111                    println!("Applying {stash:?}");
    112                }
    113                ("pop", sub_matches) => {
    114                    let stash = sub_matches.get_one::<String>("STASH");
    115                    println!("Popping {stash:?}");
    116                }
    117                ("push", sub_matches) => {
    118                    let message = sub_matches.get_one::<String>("message");
    119                    println!("Pushing {message:?}");
    120                }
    121                (name, _) => {
    122                    unreachable!("Unsupported subcommand `{name}`")
    123                }
    124            }
    125        }
    126        Some((ext, sub_matches)) => {
    127            let args = sub_matches
    128                .get_many::<OsString>("")
    129                .into_iter()
    130                .flatten()
    131                .collect::<Vec<_>>();
    132            println!("Calling out to {ext:?} with {args:?}");
    133        }
    134        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable!()
    135    }
    136
    137    // Continued program logic goes here...
    138}

Source

#### pub fn get_occurrences<T>(&self, id: &str) -> Option<OccurrencesRef<'_, T>>
where T: Any + Clone + Send + Sync + 'static,

Iterate over the values passed to each occurrence of an option.

Each item is itself an iterator containing the arguments passed to a single occurrence of the option.

If the option doesn’t support multiple occurrences, or there was only a single occurrence, the iterator will only contain a single item.

Returns `None` if the option wasn’t present.

##### §Panics

If the argument definition and access mismatch (debug builds). To handle this case programmatically, see `ArgMatches::try_get_occurrences`.

##### §Examples

    let m = Command::new("myprog")
        .arg(Arg::new("x")
            .short('x')
            .num_args(2)
            .action(ArgAction::Append)
            .value_parser(value_parser!(String)))
        .get_matches_from(vec![
            "myprog", "-x", "a", "b", "-x", "c", "d"]);
    let vals: Vec<Vec<&String>> = m.get_occurrences("x").unwrap().map(Iterator::collect).collect();
    assert_eq!(vals, [["a", "b"], ["c", "d"]]);

Source

#### pub fn get_raw(&self, id: &str) -> Option<RawValues<'_>>

Iterate over the original argument values.

An `OsStr` on Unix-like systems is any series of bytes, regardless of whether or not they contain valid UTF-8. Since `String`s in Rust are guaranteed to be valid UTF-8, a valid filename on a Unix system as an argument value may contain invalid UTF-8.

Returns `None` if the option wasn’t present.

##### §Panic

If the argument definition and access mismatch. To handle this case programmatically, see `ArgMatches::try_get_raw`.

##### §Examples

    use std::path::PathBuf;

    let m = Command::new("utf8")
        .arg(arg!(<arg> ... "some arg").value_parser(value_parser!(PathBuf)))
        .get_matches_from(vec![OsString::from("myprog"),
                                    // "Hi"
                                    OsString::from_vec(vec![b'H', b'i']),
                                    // "{0xe9}!"
                                    OsString::from_vec(vec![0xe9, b'!'])]);

    let mut itr = m.get_raw("arg")
        .expect("`port`is required")
        .into_iter();
    assert_eq!(itr.next(), Some(OsStr::new("Hi")));
    assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!'])));
    assert_eq!(itr.next(), None);

Source

#### pub fn get_raw_occurrences(&self, id: &str) -> Option<RawOccurrences<'_>>

Iterate over the original values for each occurrence of an option.

Similar to `ArgMatches::get_occurrences` but returns raw values.

An `OsStr` on Unix-like systems is any series of bytes, regardless of whether or not they contain valid UTF-8. Since `String`s in Rust are guaranteed to be valid UTF-8, a valid filename on a Unix system as an argument value may contain invalid UTF-8.

Returns `None` if the option wasn’t present.

##### §Panic

If the argument definition and access mismatch. To handle this case programmatically, see `ArgMatches::try_get_raw_occurrences`.

##### §Examples

    use std::path::PathBuf;

    let m = Command::new("myprog")
        .arg(Arg::new("x")
            .short('x')
            .num_args(2)
            .action(ArgAction::Append)
            .value_parser(value_parser!(PathBuf)))
        .get_matches_from(vec![OsString::from("myprog"),
                                OsString::from("-x"),
                                OsString::from("a"), OsString::from("b"),
                                OsString::from("-x"),
                                OsString::from("c"),
                                // "{0xe9}!"
                                OsString::from_vec(vec![0xe9, b'!'])]);
    let mut itr = m.get_raw_occurrences("x")
        .expect("`-x`is required")
        .map(Iterator::collect::<Vec<_>>);
    assert_eq!(itr.next(), Some(vec![OsStr::new("a"), OsStr::new("b")]));
    assert_eq!(itr.next(), Some(vec![OsStr::new("c"), OsStr::from_bytes(&[0xe9, b'!'])]));
    assert_eq!(itr.next(), None);

Source

#### pub fn remove_one<T>(&mut self, id: &str) -> Option<T>
where T: Any + Clone + Send + Sync + 'static,

Returns the value of a specific option or positional argument.

i.e. an argument that takes an additional value at runtime.

Returns an error if the wrong type was used. No item will have been removed.

Returns `None` if the option wasn’t present.

NOTE: This will always return `Some(value)` if `default_value` has been set. `ArgMatches::value_source` can be used to check if a value is present at runtime.

##### §Panic

If the argument definition and access mismatch. To handle this case programmatically, see `ArgMatches::try_remove_one`.

##### §Examples

    let mut m = Command::new("myprog")
        .arg(Arg::new("file")
            .required(true)
            .action(ArgAction::Set))
        .get_matches_from(vec![
            "myprog", "file.txt",
        ]);
    let vals: String = m.remove_one("file")
        .expect("`file`is required");
    assert_eq!(vals, "file.txt");

##### Examples found in repository?

examples/derive_ref/flatten_hand_args.rs (line 20)

    16    fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result<Self, Error> {
    17        Ok(Self {
    18            foo: matches.get_flag("foo"),
    19            bar: matches.get_flag("bar"),
    20            quuz: matches.remove_one::<String>("quuz"),
    21        })
    22    }
    23    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
    24        let mut matches = matches.clone();
    25        self.update_from_arg_matches_mut(&mut matches)
    26    }
    27    fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> {
    28        self.foo |= matches.get_flag("foo");
    29        self.bar |= matches.get_flag("bar");
    30        if let Some(quuz) = matches.remove_one::<String>("quuz") {
    31            self.quuz = Some(quuz);
    32        }
    33        Ok(())
    34    }

Source

#### pub fn remove_many<T>(&mut self, id: &str) -> Option<Values<T>>
where T: Any + Clone + Send + Sync + 'static,

Return values of a specific option or positional argument.

i.e. an argument that takes multiple values at runtime.

Returns an error if the wrong type was used. No item will have been removed.

Returns `None` if the option wasn’t present.

##### §Panic

If the argument definition and access mismatch. To handle this case programmatically, see `ArgMatches::try_remove_many`.

##### §Examples

    let mut m = Command::new("myprog")
        .arg(Arg::new("file")
            .action(ArgAction::Append)
            .num_args(1..)
            .required(true))
        .get_matches_from(vec![
            "myprog", "file1.txt", "file2.txt", "file3.txt", "file4.txt",
        ]);
    let vals: Vec<String> = m.remove_many("file")
        .expect("`file`is required")
        .collect();
    assert_eq!(vals, ["file1.txt", "file2.txt", "file3.txt", "file4.txt"]);

Source

#### pub fn remove_occurrences<T>(&mut self, id: &str) -> Option<Occurrences<T>>
where T: Any + Clone + Send + Sync + 'static,

Return values for each occurrence of an option.

Each item is itself an iterator containing the arguments passed to a single occurrence of the option.

If the option doesn’t support multiple occurrences, or there was only a single occurrence, the iterator will only contain a single item.

Returns `None` if the option wasn’t present.

##### §Panic

If the argument definition and access mismatch. To handle this case programmatically, see `ArgMatches::try_remove_occurrences`.

##### §Examples

    let mut m = Command::new("myprog")
        .arg(Arg::new("x")
            .short('x')
            .num_args(2)
            .action(ArgAction::Append)
            .value_parser(value_parser!(String)))
        .get_matches_from(vec![
            "myprog", "-x", "a", "b", "-x", "c", "d"]);
    let vals: Vec<Vec<String>> = m.remove_occurrences("x").unwrap().map(Iterator::collect).collect();
    assert_eq!(vals, [["a", "b"], ["c", "d"]]);

Source

#### pub fn contains_id(&self, id: &str) -> bool

Check if values are present for the argument or group id

NOTE: This will always return `true` if `default_value` has been set. `ArgMatches::value_source` can be used to check if a value is present at runtime.

##### §Panics

If `id` is not a valid argument or group name (debug builds). To handle this case programmatically, see `ArgMatches::try_contains_id`.

##### §Examples

    let m = Command::new("myprog")
        .arg(Arg::new("debug")
            .short('d')
            .action(ArgAction::SetTrue))
        .get_matches_from(vec![
            "myprog", "-d"
        ]);

    assert!(m.contains_id("debug"));

##### Examples found in repository?

examples/multicall-busybox.rs (line 37)

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

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

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

Source

#### pub fn ids(&self) -> IdsRef<'_> ⓘ

Iterate over `Arg` and `ArgGroup` `Id`s via `ArgMatches::ids`.

##### §Examples

    let m = Command::new("myprog")
        .arg(arg!(--color <when>)
            .value_parser(["auto", "always", "never"]))
        .arg(arg!(--config <path>)
            .value_parser(value_parser!(std::path::PathBuf)))
        .get_matches_from(["myprog", "--config=config.toml", "--color=auto"]);
    assert_eq!(m.ids().len(), 2);
    assert_eq!(
        m.ids()
            .map(|id| id.as_str())
            .collect::<Vec<_>>(),
        ["config", "color"]
    );

Source

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

Check if any `Arg`s were present on the command line

See `ArgMatches::subcommand_name()` or `ArgMatches::subcommand()` to check if a subcommand was present on the command line.

##### §Examples

    let mut cmd = Command::new("myapp")
        .arg(Arg::new("output")
            .action(ArgAction::Set));

    let m = cmd
        .try_get_matches_from_mut(vec!["myapp", "something"])
        .unwrap();
    assert!(m.args_present());

    let m = cmd
        .try_get_matches_from_mut(vec!["myapp"])
        .unwrap();
    assert!(! m.args_present());

Source

#### pub fn value_source(&self, id: &str) -> Option<ValueSource>

Report where argument value came from

##### §Panics

If `id` is not a valid argument or group id (debug builds).

##### §Examples

    let m = Command::new("myprog")
        .arg(Arg::new("debug")
            .short('d')
            .action(ArgAction::SetTrue))
        .get_matches_from(vec![
            "myprog", "-d"
        ]);

    assert_eq!(m.value_source("debug"), Some(ValueSource::CommandLine));

Source

#### pub fn index_of(&self, id: &str) -> Option<usize>

The first index of that an argument showed up.

Indices are similar to argv indices, but are not exactly 1:1.

For flags (i.e. those arguments which don’t have an associated value), indices refer to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices refer to the values `-o val` would therefore not represent two distinct indices, only the index for `val` would be recorded. This is by design.

Besides the flag/option discrepancy, the primary difference between an argv index and clap index, is that clap continues counting once all arguments have properly separated, whereas an argv index does not.

The examples should clear this up.

NOTE: If an argument is allowed multiple times, this method will only give the first index. See `ArgMatches::indices_of`.

##### §Panics

If `id` is not a valid argument or group id (debug builds).

##### §Examples

The argv indices are listed in the comments below. See how they correspond to the clap indices. Note that if it’s not listed in a clap index, this is because it’s not saved in in an `ArgMatches` struct for querying.

    let m = Command::new("myapp")
        .arg(Arg::new("flag")
            .short('f')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("option")
            .short('o')
            .action(ArgAction::Set))
        .get_matches_from(vec!["myapp", "-f", "-o", "val"]);
               // ARGV indices: ^0       ^1    ^2    ^3
               // clap indices:          ^1          ^3

    assert_eq!(m.index_of("flag"), Some(1));
    assert_eq!(m.index_of("option"), Some(3));

Now notice, if we use one of the other styles of options:

    let m = Command::new("myapp")
        .arg(Arg::new("flag")
            .short('f')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("option")
            .short('o')
            .action(ArgAction::Set))
        .get_matches_from(vec!["myapp", "-f", "-o=val"]);
               // ARGV indices: ^0       ^1    ^2
               // clap indices:          ^1       ^3

    assert_eq!(m.index_of("flag"), Some(1));
    assert_eq!(m.index_of("option"), Some(3));

Things become much more complicated, or clear if we look at a more complex combination of flags. Let’s also throw in the final option style for good measure.

    let m = Command::new("myapp")
        .arg(Arg::new("flag")
            .short('f')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("flag2")
            .short('F')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("flag3")
            .short('z')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("option")
            .short('o')
            .action(ArgAction::Set))
        .get_matches_from(vec!["myapp", "-fzF", "-oval"]);
               // ARGV indices: ^0      ^1       ^2
               // clap indices:         ^1,2,3    ^5
               //
               // clap sees the above as 'myapp -f -z -F -o val'
               //                         ^0    ^1 ^2 ^3 ^4 ^5
    assert_eq!(m.index_of("flag"), Some(1));
    assert_eq!(m.index_of("flag2"), Some(3));
    assert_eq!(m.index_of("flag3"), Some(2));
    assert_eq!(m.index_of("option"), Some(5));

One final combination of flags/options to see how they combine:

    let m = Command::new("myapp")
        .arg(Arg::new("flag")
            .short('f')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("flag2")
            .short('F')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("flag3")
            .short('z')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("option")
            .short('o')
            .action(ArgAction::Set))
        .get_matches_from(vec!["myapp", "-fzFoval"]);
               // ARGV indices: ^0       ^1
               // clap indices:          ^1,2,3^5
               //
               // clap sees the above as 'myapp -f -z -F -o val'
               //                         ^0    ^1 ^2 ^3 ^4 ^5
    assert_eq!(m.index_of("flag"), Some(1));
    assert_eq!(m.index_of("flag2"), Some(3));
    assert_eq!(m.index_of("flag3"), Some(2));
    assert_eq!(m.index_of("option"), Some(5));

The last part to mention is when values are sent in multiple groups with a delimiter.

    let m = Command::new("myapp")
        .arg(Arg::new("option")
            .short('o')
            .value_delimiter(',')
            .num_args(1..))
        .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
               // ARGV indices: ^0       ^1
               // clap indices:             ^2   ^3   ^4
               //
               // clap sees the above as 'myapp -o val1 val2 val3'
               //                         ^0    ^1 ^2   ^3   ^4
    assert_eq!(m.index_of("option"), Some(2));
    assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]);

Source

#### pub fn indices_of(&self, id: &str) -> Option<Indices<'_>>

All indices an argument appeared at when parsing.

Indices are similar to argv indices, but are not exactly 1:1.

For flags (i.e. those arguments which don’t have an associated value), indices refer to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices refer to the values `-o val` would therefore not represent two distinct indices, only the index for `val` would be recorded. This is by design.

NOTE: For more information about how clap indices compared to argv indices, see `ArgMatches::index_of`

##### §Panics

If `id` is not a valid argument or group id (debug builds).

##### §Examples

    let m = Command::new("myapp")
        .arg(Arg::new("option")
            .short('o')
            .value_delimiter(','))
        .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
               // ARGV indices: ^0       ^1
               // clap indices:             ^2   ^3   ^4
               //
               // clap sees the above as 'myapp -o val1 val2 val3'
               //                         ^0    ^1 ^2   ^3   ^4
    assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]);

Another quick example is when flags and options are used together

    let m = Command::new("myapp")
        .arg(Arg::new("option")
            .short('o')
            .action(ArgAction::Set)
            .action(ArgAction::Append))
        .arg(Arg::new("flag")
            .short('f')
            .action(ArgAction::Count))
        .get_matches_from(vec!["myapp", "-o", "val1", "-f", "-o", "val2", "-f"]);
               // ARGV indices: ^0       ^1    ^2      ^3    ^4    ^5      ^6
               // clap indices:                ^2      ^3          ^5      ^6

    assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 5]);
    assert_eq!(m.indices_of("flag").unwrap().collect::<Vec<_>>(), &[6]);

One final example, which is an odd case; if we don’t use value delimiter as we did with the first example above instead of `val1`, `val2` and `val3` all being distinc values, they would all be a single value of `val1,val2,val3`, in which case they’d only receive a single index.

    let m = Command::new("myapp")
        .arg(Arg::new("option")
            .short('o')
            .action(ArgAction::Set)
            .num_args(1..))
        .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
               // ARGV indices: ^0       ^1
               // clap indices:             ^2
               //
               // clap sees the above as 'myapp -o "val1,val2,val3"'
               //                         ^0    ^1  ^2
    assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2]);

Source§

### impl ArgMatches

#### §Subcommands

Source

#### pub fn subcommand(&self) -> Option<(&str, &ArgMatches)>

The name and `ArgMatches` of the current subcommand.

Subcommand values are put in a child `ArgMatches`

Returns `None` if the subcommand wasn’t present at runtime,

##### §Examples

     let app_m = Command::new("git")
         .subcommand(Command::new("clone"))
         .subcommand(Command::new("push"))
         .subcommand(Command::new("commit"))
         .get_matches();

    match app_m.subcommand() {
        Some(("clone",  sub_m)) => {}, // clone was used
        Some(("push",   sub_m)) => {}, // push was used
        Some(("commit", sub_m)) => {}, // commit was used
        _                       => {}, // Either no subcommand or one not tested for...
    }

Another useful scenario is when you want to support third party, or external, subcommands. In these cases you can’t know the subcommand name ahead of time, so use a variable instead with pattern matching!

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

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

##### Examples found in repository?

examples/derive_ref/hand_subcommand.rs (line 24)

    23    fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
    24        match matches.subcommand() {
    25            Some(("add", args)) => Ok(Self::Add(AddArgs::from_arg_matches(args)?)),
    26            Some(("remove", args)) => Ok(Self::Remove(RemoveArgs::from_arg_matches(args)?)),
    27            Some((_, _)) => Err(Error::raw(
    28                ErrorKind::InvalidSubcommand,
    29                "Valid subcommands are `add` and `remove`",
    30            )),
    31            None => Err(Error::raw(
    32                ErrorKind::MissingSubcommand,
    33                "Valid subcommands are `add` and `remove`",
    34            )),
    35        }
    36    }
    37    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
    38        match matches.subcommand() {
    39            Some(("add", args)) => *self = Self::Add(AddArgs::from_arg_matches(args)?),
    40            Some(("remove", args)) => *self = Self::Remove(RemoveArgs::from_arg_matches(args)?),
    41            Some((_, _)) => {
    42                return Err(Error::raw(
    43                    ErrorKind::InvalidSubcommand,
    44                    "Valid subcommands are `add` and `remove`",
    45                ));
    46            }
    47            None => (),
    48        };
    49        Ok(())
    50    }

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

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

examples/multicall-busybox.rs (line 35)

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

examples/pacman.rs (line 74)

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

examples/git.rs (line 63)

    60fn main() {
    61    let matches = cli().get_matches();
    62
    63    match matches.subcommand() {
    64        Some(("clone", sub_matches)) => {
    65            println!(
    66                "Cloning {}",
    67                sub_matches.get_one::<String>("REMOTE").expect("required")
    68            );
    69        }
    70        Some(("diff", sub_matches)) => {
    71            let color = sub_matches
    72                .get_one::<String>("color")
    73                .map(|s| s.as_str())
    74                .expect("defaulted in clap");
    75
    76            let mut base = sub_matches.get_one::<String>("base").map(|s| s.as_str());
    77            let mut head = sub_matches.get_one::<String>("head").map(|s| s.as_str());
    78            let mut path = sub_matches.get_one::<String>("path").map(|s| s.as_str());
    79            if path.is_none() {
    80                path = head;
    81                head = None;
    82                if path.is_none() {
    83                    path = base;
    84                    base = None;
    85                }
    86            }
    87            let base = base.unwrap_or("stage");
    88            let head = head.unwrap_or("worktree");
    89            let path = path.unwrap_or("");
    90            println!("Diffing {base}..{head} {path} (color={color})");
    91        }
    92        Some(("push", sub_matches)) => {
    93            println!(
    94                "Pushing to {}",
    95                sub_matches.get_one::<String>("REMOTE").expect("required")
    96            );
    97        }
    98        Some(("add", sub_matches)) => {
    99            let paths = sub_matches
    100                .get_many::<PathBuf>("PATH")
    101                .into_iter()
    102                .flatten()
    103                .collect::<Vec<_>>();
    104            println!("Adding {paths:?}");
    105        }
    106        Some(("stash", sub_matches)) => {
    107            let stash_command = sub_matches.subcommand().unwrap_or(("push", sub_matches));
    108            match stash_command {
    109                ("apply", sub_matches) => {
    110                    let stash = sub_matches.get_one::<String>("STASH");
    111                    println!("Applying {stash:?}");
    112                }
    113                ("pop", sub_matches) => {
    114                    let stash = sub_matches.get_one::<String>("STASH");
    115                    println!("Popping {stash:?}");
    116                }
    117                ("push", sub_matches) => {
    118                    let message = sub_matches.get_one::<String>("message");
    119                    println!("Pushing {message:?}");
    120                }
    121                (name, _) => {
    122                    unreachable!("Unsupported subcommand `{name}`")
    123                }
    124            }
    125        }
    126        Some((ext, sub_matches)) => {
    127            let args = sub_matches
    128                .get_many::<OsString>("")
    129                .into_iter()
    130                .flatten()
    131                .collect::<Vec<_>>();
    132            println!("Calling out to {ext:?} with {args:?}");
    133        }
    134        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable!()
    135    }
    136
    137    // Continued program logic goes here...
    138}

Source

#### pub fn remove_subcommand(&mut self) -> Option<(String, ArgMatches)>

Return the name and `ArgMatches` of the current subcommand.

Subcommand values are put in a child `ArgMatches`

Returns `None` if the subcommand wasn’t present at runtime,

##### §Examples

     let mut app_m = Command::new("git")
         .subcommand(Command::new("clone"))
         .subcommand(Command::new("push"))
         .subcommand(Command::new("commit"))
         .subcommand_required(true)
         .get_matches();

    let (name, sub_m) = app_m.remove_subcommand().expect("required");
    match (name.as_str(), sub_m) {
        ("clone",  sub_m) => {}, // clone was used
        ("push",   sub_m) => {}, // push was used
        ("commit", sub_m) => {}, // commit was used
        (name, _)         => unimplemented!("{name}"),
    }

Another useful scenario is when you want to support third party, or external, subcommands. In these cases you can’t know the subcommand name ahead of time, so use a variable instead with pattern matching!

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

    // All trailing arguments will be stored under the subcommand's sub-matches using an empty
    // string argument name
    match app_m.remove_subcommand() {
        Some((external, mut sub_m)) => {
             let ext_args: Vec<OsString> = sub_m.remove_many("")
                .expect("`file`is required")
                .collect();
             assert_eq!(external, "subcmd");
             assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
        },
        _ => {},
    }

Source

#### pub fn subcommand_matches(&self, name: &str) -> Option<&ArgMatches>

The `ArgMatches` for the current subcommand.

Subcommand values are put in a child `ArgMatches`

Returns `None` if the subcommand wasn’t present at runtime,

##### §Panics

If `id` is not a valid subcommand (debug builds).

##### §Examples

    let app_m = Command::new("myprog")
        .arg(Arg::new("debug")
            .short('d')
            .action(ArgAction::SetTrue)
        )
        .subcommand(Command::new("test")
            .arg(Arg::new("opt")
                .long("option")
                .action(ArgAction::Set)))
        .get_matches_from(vec![
            "myprog", "-d", "test", "--option", "val"
        ]);

    // Both parent commands, and child subcommands can have arguments present at the same times
    assert!(app_m.get_flag("debug"));

    // Get the subcommand's ArgMatches instance
    if let Some(sub_m) = app_m.subcommand_matches("test") {
        // Use the struct like normal
        assert_eq!(sub_m.get_one::<String>("opt").map(|s| s.as_str()), Some("val"));
    }

Source

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

The name of the current subcommand.

Returns `None` if the subcommand wasn’t present at runtime,

##### §Examples

     let app_m = Command::new("git")
         .subcommand(Command::new("clone"))
         .subcommand(Command::new("push"))
         .subcommand(Command::new("commit"))
         .get_matches();

    match app_m.subcommand_name() {
        Some("clone")  => {}, // clone was used
        Some("push")   => {}, // push was used
        Some("commit") => {}, // commit was used
        _              => {}, // Either no subcommand or one not tested for...
    }

##### Examples found in repository?

examples/multicall-hostname.rs (line 12)

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

Source§

### impl ArgMatches

#### §Advanced

Source

#### pub fn try_get_one<T>(&self, id: &str) -> Result<Option<&T>, MatchesError>
where T: Any + Clone + Send + Sync + 'static,

Non-panicking version of `ArgMatches::get_one`

Source

#### pub fn try_get_many<T>( &self, id: &str, ) -> Result<Option<ValuesRef<'_, T>>, MatchesError>
where T: Any + Clone + Send + Sync + 'static,

Non-panicking version of `ArgMatches::get_many`

Source

#### pub fn try_get_occurrences<T>( &self, id: &str, ) -> Result<Option<OccurrencesRef<'_, T>>, MatchesError>
where T: Any + Clone + Send + Sync + 'static,

Non-panicking version of `ArgMatches::get_occurrences`

Source

#### pub fn try_get_raw( &self, id: &str, ) -> Result<Option<RawValues<'_>>, MatchesError>

Non-panicking version of `ArgMatches::get_raw`

Source

#### pub fn try_get_raw_occurrences( &self, id: &str, ) -> Result<Option<RawOccurrences<'_>>, MatchesError>

Non-panicking version of `ArgMatches::get_raw_occurrences`

Source

#### pub fn try_remove_one<T>(&mut self, id: &str) -> Result<Option<T>, MatchesError>
where T: Any + Clone + Send + Sync + 'static,

Non-panicking version of `ArgMatches::remove_one`

Source

#### pub fn try_remove_many<T>( &mut self, id: &str, ) -> Result<Option<Values<T>>, MatchesError>
where T: Any + Clone + Send + Sync + 'static,

Non-panicking version of `ArgMatches::remove_many`

Source

#### pub fn try_remove_occurrences<T>( &mut self, id: &str, ) -> Result<Option<Occurrences<T>>, MatchesError>
where T: Any + Clone + Send + Sync + 'static,

Non-panicking version of `ArgMatches::remove_occurrences`

Source

#### pub fn try_contains_id(&self, id: &str) -> Result<bool, MatchesError>

Non-panicking version of `ArgMatches::contains_id`

Source

#### pub fn try_clear_id(&mut self, id: &str) -> Result<bool, MatchesError>

Clears the values for the given `id`

Alternative to `try_remove_*` when the type is not known.

Returns `Err([``MatchesError``])` if the given `id` isn’t valid for current `ArgMatches` instance.

Returns `Ok(true)` if there were any matches with the given `id`, `Ok(false)` otherwise.

## Trait Implementations§

Source§

### impl Clone for ArgMatches

Source§

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

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

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

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

### impl Debug for ArgMatches

Source§

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

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

### impl Default for ArgMatches

Source§

#### fn default() -> ArgMatches

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

### impl Eq for ArgMatches

Source§

### impl PartialEq for ArgMatches

Source§

#### fn eq(&self, other: &ArgMatches) -> bool

Equality operator `==`. Read more
1.0.0 (const: unstable) · Source§

#### fn ne(&self, other: &Rhs) -> bool

Inequality operator `!=`. Read more
Source§

### impl StructuralPartialEq for ArgMatches

## Auto Trait Implementations§

§

### impl !RefUnwindSafe for ArgMatches

§

### impl !UnwindSafe for ArgMatches

§

### impl Freeze for ArgMatches

§

### impl Send for ArgMatches

§

### impl Sync for ArgMatches

§

### impl Unpin for ArgMatches

§

### impl UnsafeUnpin for ArgMatches

## Blanket Implementations§

Source§

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

Source§

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

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

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

Source§

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

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

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

Source§

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

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

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

Source§

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

Returns the argument unchanged.

Source§

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

Source§

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

Calls `U::from(self)`.

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

Source§

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

Source§

#### type Owned = T

The resulting type after obtaining ownership.
Source§

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

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

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

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

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

Source§

#### type Error = Infallible

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

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

Performs the conversion.
Source§

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

Source§

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

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

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

Performs the conversion.