docs(examples): add examples on default values and specific value sets

This commit is contained in:
Kevin K 2015-03-28 21:19:51 -04:00
parent ee8e0f0046
commit 62ec95aa1d
2 changed files with 53 additions and 0 deletions

View file

@ -0,0 +1,20 @@
extern crate clap;
use clap::{App, Arg};
fn main() {
// You can get a "default value" like feature by using Option<T>'s .unwrap_or() method
//
// Let's assume you have -c <config> argument to allow users to specify a configuration file
// but you also want to support a default file, if none is specified.
let matches = App::new("myapp").about("does awesome things")
.arg(Arg::new("CONFIG")
.help("The config file to use (default is \"config.json\")")
.short("c")
.takes_value(true))
.get_matches();
let config_file = matches.value_of("CONFIG").unwrap_or("config.json");
// use config_file here...
}

View file

@ -0,0 +1,33 @@
extern crate clap;
use clap::{App, Arg};
fn main() {
// If you have arguments of specific values you want to test for, you can use the
// .possible_values() method of Arg
//
// This allows you specify the valid values for that argument. If the user does not use one of
// those specific values, they will receive a graceful exit with error message informing them
// of the mistake, and what the possible valid values are
//
// For this example, assume you want one positional argument of either "fast" or "slow"
// i.e. the only possible ways to run the program are "myprog fast" or "myprog slow"
let matches = App::new("myapp").about("does awesome things")
.arg(Arg::new("MODE")
.help("What mode to run the program in")
.index(1)
.possible_values(vec!["fast", "slow"])
.required(true))
.get_matches();
// Note, it's safe to call unwrap() because the arg is required
match matches.value_of("MODE").unwrap() {
"fast" => {
// Do fast things...
},
"slow" => {
// Do slow things...
},
_ => unreachable!()
}
}