Trait FromArgMatches

trait FromArgMatches: Sized

Converts an instance of ArgMatches to a user-defined container.

Derived as part of Parser, Args, and Subcommand.

Required Methods

fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error>

Instantiate Self from ArgMatches, parsing the arguments as needed.

Motivation: If our application had two CLI options, --name <STRING> and the flag --debug, we may create a struct as follows:

# #[cfg(feature = "derive")] {
struct Context {
    name: String,
    debug: bool
}
# }

We then need to convert the ArgMatches that clap generated into our struct. from_arg_matches serves as the equivalent of:

# #[cfg(feature = "derive")] {
# use clap::ArgMatches;
# struct Context {
#   name: String,
#   debug: bool
# }
impl From<ArgMatches> for Context {
   fn from(m: ArgMatches) -> Self {
       Context {
           name: m.get_one::<String>("name").unwrap().clone(),
           debug: m.get_flag("debug"),
       }
   }
}
# }
fn update_from_arg_matches(self: &mut Self, matches: &ArgMatches) -> Result<(), Error>

Assign values from ArgMatches to self.

Provided Methods

fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result<Self, Error>

Instantiate Self from ArgMatches, parsing the arguments as needed.

Motivation: If our application had two CLI options, --name <STRING> and the flag --debug, we may create a struct as follows:

# #[cfg(feature = "derive")] {
struct Context {
    name: String,
    debug: bool
}
# }

We then need to convert the ArgMatches that clap generated into our struct. from_arg_matches_mut serves as the equivalent of:

# #[cfg(feature = "derive")] {
# use clap::ArgMatches;
# struct Context {
#   name: String,
#   debug: bool
# }
impl From<ArgMatches> for Context {
   fn from(m: ArgMatches) -> Self {
       Context {
           name: m.get_one::<String>("name").unwrap().to_string(),
           debug: m.get_flag("debug"),
       }
   }
}
# }
fn update_from_arg_matches_mut(self: &mut Self, matches: &mut ArgMatches) -> Result<(), Error>

Assign values from ArgMatches to self.

Implementors