Struct ArgMatches
struct ArgMatches { ... }
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
# use clap_builder as clap;
# use clap::{Command, Arg, ArgAction};
# use clap::parser::ValueSource;
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
impl ArgMatches
fn get_one<T: Any + Clone + Send + Sync + 'static>(self: &Self, id: &str) -> Option<&T>Gets the value of a specific option or positional argument.
i.e. an argument that [takes an additional value][crate::Arg::num_args] at runtime.
Returns an error if the wrong type was used.
Returns
Noneif the option wasn't present.NOTE: This will always return
Some(value)ifdefault_valuehas been set.ArgMatches::value_sourcecan 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
# use clap_builder as clap; # use ; let m = new .arg .get_matches_from; let port: usize = *m .get_one .expect; assert_eq!;fn get_count(self: &Self, id: &str) -> u8Gets the value of a specific [
ArgAction::Count][crate::ArgAction::Count] flagPanic
If the argument's action is not [
ArgAction::Count][crate::ArgAction::Count]Examples
# use clap_builder as clap; # use Command; # use Arg; let cmd = new .arg; let matches = cmd.clone.try_get_matches_from.unwrap; assert_eq!;fn get_flag(self: &Self, id: &str) -> boolGets the value of a specific [
ArgAction::SetTrue][crate::ArgAction::SetTrue] or [ArgAction::SetFalse][crate::ArgAction::SetFalse] flagPanic
If the argument's action is not [
ArgAction::SetTrue][crate::ArgAction::SetTrue] or [ArgAction::SetFalse][crate::ArgAction::SetFalse]Examples
# use clap_builder as clap; # use Command; # use Arg; let cmd = new .arg; let matches = cmd.clone.try_get_matches_from.unwrap; assert!; assert_eq!;fn get_many<T: Any + Clone + Send + Sync + 'static>(self: &Self, id: &str) -> Option<ValuesRef<'_, T>>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
Noneif the option wasn't present.Panic
If the argument definition and access mismatch. To handle this case programmatically, see
ArgMatches::try_get_many.Examples
# use clap_builder as clap; # use ; let m = new .arg .get_matches_from; let vals: = m.get_many .expect .copied .collect; assert_eq!;fn get_occurrences<T: Any + Clone + Send + Sync + 'static>(self: &Self, id: &str) -> Option<OccurrencesRef<'_, T>>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
Noneif 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
# use clap_builder as clap; # use ; let m = new .arg .get_matches_from; let vals: = m.get_occurrences.unwrap.map.collect; assert_eq!;fn get_raw(self: &Self, id: &str) -> Option<RawValues<'_>>Iterate over the original argument values.
An
OsStron Unix-like systems is any series of bytes, regardless of whether or not they contain valid UTF-8. SinceStrings 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
Noneif the option wasn't present.Panic
If the argument definition and access mismatch. To handle this case programmatically, see
ArgMatches::try_get_raw.Examples
#fn get_raw_occurrences(self: &Self, id: &str) -> Option<RawOccurrences<'_>>Iterate over the original values for each occurrence of an option.
Similar to
ArgMatches::get_occurrencesbut returns raw values.An
OsStron Unix-like systems is any series of bytes, regardless of whether or not they contain valid UTF-8. SinceStrings 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
Noneif 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
#fn remove_one<T: Any + Clone + Send + Sync + 'static>(self: &mut Self, id: &str) -> Option<T>Returns the value of a specific option or positional argument.
i.e. an argument that [takes an additional value][crate::Arg::num_args] at runtime.
Returns an error if the wrong type was used. No item will have been removed.
Returns
Noneif the option wasn't present.NOTE: This will always return
Some(value)ifdefault_valuehas been set.ArgMatches::value_sourcecan 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
# use clap_builder as clap; # use ; let mut m = new .arg .get_matches_from; let vals: String = m.remove_one .expect; assert_eq!;fn remove_many<T: Any + Clone + Send + Sync + 'static>(self: &mut Self, id: &str) -> Option<Values<T>>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
Noneif the option wasn't present.Panic
If the argument definition and access mismatch. To handle this case programmatically, see
ArgMatches::try_remove_many.Examples
# use clap_builder as clap; # use ; let mut m = new .arg .get_matches_from; let vals: = m.remove_many .expect .collect; assert_eq!;fn remove_occurrences<T: Any + Clone + Send + Sync + 'static>(self: &mut Self, id: &str) -> Option<Occurrences<T>>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
Noneif the option wasn't present.Panic
If the argument definition and access mismatch. To handle this case programmatically, see
ArgMatches::try_remove_occurrences.Examples
# use clap_builder as clap; # use ; let mut m = new .arg .get_matches_from; let vals: = m.remove_occurrences.unwrap.map.collect; assert_eq!;fn contains_id(self: &Self, id: &str) -> boolCheck if values are present for the argument or group id
NOTE: This will always return
trueifdefault_valuehas been set.ArgMatches::value_sourcecan be used to check if a value is present at runtime.Panics
If
idis not a valid argument or group name (debug builds). To handle this case programmatically, seeArgMatches::try_contains_id.Examples
# use clap_builder as clap; # use ; let m = new .arg .get_matches_from; assert!;fn ids(self: &Self) -> IdsRef<'_>Iterate over [
Arg][crate::Arg] and [ArgGroup][crate::ArgGroup]Ids viaArgMatches::ids.Examples
# use clap_builder as clap; # use ; let m = new .arg .arg .get_matches_from; assert_eq!; assert_eq!;fn args_present(self: &Self) -> boolCheck if any args were present on the command line
Examples
# use clap_builder as clap; # use ; let mut cmd = new .arg; let m = cmd .try_get_matches_from_mut .unwrap; assert!; let m = cmd .try_get_matches_from_mut .unwrap; assert!;fn value_source(self: &Self, id: &str) -> Option<ValueSource>Report where argument value came from
Panics
If
idis not a valid argument or group id (debug builds).Examples
# use clap_builder as clap; # use ; # use ValueSource; let m = new .arg .get_matches_from; assert_eq!;fn index_of(self: &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 valwould therefore not represent two distinct indices, only the index forvalwould 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
idis 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
ArgMatchesstruct for querying.# use clap_builder as clap; # use ; let m = new .arg .arg .get_matches_from; // ARGV indices: ^0 ^1 ^2 ^3 // clap indices: ^1 ^3 assert_eq!; assert_eq!;Now notice, if we use one of the other styles of options:
# use clap_builder as clap; # use ; let m = new .arg .arg .get_matches_from; // ARGV indices: ^0 ^1 ^2 // clap indices: ^1 ^3 assert_eq!; assert_eq!;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.
# use clap_builder as clap; # use ; let m = new .arg .arg .arg .arg .get_matches_from; // 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!; assert_eq!; assert_eq!; assert_eq!;One final combination of flags/options to see how they combine:
# use clap_builder as clap; # use ; let m = new .arg .arg .arg .arg .get_matches_from; // 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!; assert_eq!; assert_eq!; assert_eq!;The last part to mention is when values are sent in multiple groups with a delimiter.
# use clap_builder as clap; # use ; let m = new .arg .get_matches_from; // 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!; assert_eq!;fn indices_of(self: &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 valwould therefore not represent two distinct indices, only the index forvalwould be recorded. This is by design.NOTE: For more information about how clap indices compared to argv indices, see
ArgMatches::index_ofPanics
If
idis not a valid argument or group id (debug builds).Examples
# use clap_builder as clap; # use ; let m = new .arg .get_matches_from; // 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!;Another quick example is when flags and options are used together
# use clap_builder as clap; # use ; let m = new .arg .arg .get_matches_from; // ARGV indices: ^0 ^1 ^2 ^3 ^4 ^5 ^6 // clap indices: ^2 ^3 ^5 ^6 assert_eq!; assert_eq!;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,val2andval3all being distinc values, they would all be a single value ofval1,val2,val3, in which case they'd only receive a single index.# use clap_builder as clap; # use ; let m = new .arg .get_matches_from; // ARGV indices: ^0 ^1 // clap indices: ^2 // // clap sees the above as 'myapp -o "val1,val2,val3"' // ^0 ^1 ^2 assert_eq!;
impl ArgMatches
fn subcommand(self: &Self) -> Option<(&str, &ArgMatches)>The name and
ArgMatchesof the current subcommand.Subcommand values are put in a child
ArgMatchesReturns
Noneif the subcommand wasn't present at runtime,Examples
# use clap_builder as clap; # use clap::{Command, Arg, }; 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!
# use clap_builder as clap; # use OsString; # use OsStr; # use Command; // Assume there is an external subcommand named "subcmd" let app_m = new .allow_external_subcommands .get_matches_from; // All trailing arguments will be stored under the subcommand's sub-matches using an empty // string argument name match app_m.subcommandfn remove_subcommand(self: &mut Self) -> Option<(String, ArgMatches)>Return the name and
ArgMatchesof the current subcommand.Subcommand values are put in a child
ArgMatchesReturns
Noneif the subcommand wasn't present at runtime,Examples
# use clap_builder as clap; # use clap::{Command, Arg, }; 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!
# use clap_builder as clap; # use OsString; # use Command; // Assume there is an external subcommand named "subcmd" let mut app_m = new .allow_external_subcommands .get_matches_from; // All trailing arguments will be stored under the subcommand's sub-matches using an empty // string argument name match app_m.remove_subcommandfn subcommand_matches(self: &Self, name: &str) -> Option<&ArgMatches>The
ArgMatchesfor the current subcommand.Subcommand values are put in a child
ArgMatchesReturns
Noneif the subcommand wasn't present at runtime,Panics
If
idis not a valid subcommand (debug builds).Examples
# use clap_builder as clap; # use ; let app_m = new .arg .subcommand .get_matches_from; // Both parent commands, and child subcommands can have arguments present at the same times assert!; // Get the subcommand's ArgMatches instance if let Some = app_m.subcommand_matchesfn subcommand_name(self: &Self) -> Option<&str>The name of the current subcommand.
Returns
Noneif the subcommand wasn't present at runtime,Examples
# use clap_builder as clap; # use clap::{Command, Arg, }; 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... }
impl ArgMatches
fn try_get_one<T: Any + Clone + Send + Sync + 'static>(self: &Self, id: &str) -> Result<Option<&T>, MatchesError>Non-panicking version of
ArgMatches::get_onefn try_get_many<T: Any + Clone + Send + Sync + 'static>(self: &Self, id: &str) -> Result<Option<ValuesRef<'_, T>>, MatchesError>Non-panicking version of
ArgMatches::get_manyfn try_get_occurrences<T: Any + Clone + Send + Sync + 'static>(self: &Self, id: &str) -> Result<Option<OccurrencesRef<'_, T>>, MatchesError>Non-panicking version of
ArgMatches::get_occurrencesfn try_get_raw(self: &Self, id: &str) -> Result<Option<RawValues<'_>>, MatchesError>Non-panicking version of
ArgMatches::get_rawfn try_get_raw_occurrences(self: &Self, id: &str) -> Result<Option<RawOccurrences<'_>>, MatchesError>Non-panicking version of
ArgMatches::get_raw_occurrencesfn try_remove_one<T: Any + Clone + Send + Sync + 'static>(self: &mut Self, id: &str) -> Result<Option<T>, MatchesError>Non-panicking version of
ArgMatches::remove_onefn try_remove_many<T: Any + Clone + Send + Sync + 'static>(self: &mut Self, id: &str) -> Result<Option<Values<T>>, MatchesError>Non-panicking version of
ArgMatches::remove_manyfn try_remove_occurrences<T: Any + Clone + Send + Sync + 'static>(self: &mut Self, id: &str) -> Result<Option<Occurrences<T>>, MatchesError>Non-panicking version of
ArgMatches::remove_occurrencesfn try_contains_id(self: &Self, id: &str) -> Result<bool, MatchesError>Non-panicking version of
ArgMatches::contains_id
impl Clone for ArgMatches
fn clone(self: &Self) -> ArgMatches
impl Debug for ArgMatches
fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<'_>) -> $crate::fmt::Result
impl Default for ArgMatches
fn default() -> ArgMatches
impl Eq for ArgMatches
impl Freeze for ArgMatches
impl PartialEq for ArgMatches
fn eq(self: &Self, other: &ArgMatches) -> bool
impl RefUnwindSafe for ArgMatches
impl Send for ArgMatches
impl StructuralPartialEq for ArgMatches
impl Sync for ArgMatches
impl Unpin for ArgMatches
impl UnwindSafe for ArgMatches
impl<T> Any for ArgMatches
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for ArgMatches
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for ArgMatches
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for ArgMatches
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> From for ArgMatches
fn from(t: T) -> TReturns the argument unchanged.
impl<T> ToOwned for ArgMatches
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T, U> Into for ArgMatches
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for ArgMatches
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for ArgMatches
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>