clap/examples/13b_EnumValuesManual.rs
Kevin K 0cc2f69839 feat(arg): allow other types besides Vec for multiple value settings
Breaking Change

Instead of requiring a Vec<&str> for various Arg::*_all() and
Arg::possible_values() methods this
commit now requires a generic IntoIterator<Item=AsRef<str>> which allows
things such as constant arrays. This change requires that any
Arg::*_all() methods be changed from vec!["val", "val"] -> let vals =
["val", "val"]; some_arg.possible_values(&vals) (or vals.iter()).

Closes #87
2015-04-29 17:52:13 -04:00

58 lines
No EOL
1.6 KiB
Rust

// If you require more complex configuration than simple_enum! provides, you can implement the
// trait manually, as in the following example.
//
// In the following example we will create an enum with 4 values, assign a positional argument
// that accepts only one of those values, and use clap to parse the argument.
//
// Start with bringing the trait into scope.
use std::str::FromStr;
// Add clap like normal
#[macro_use]
extern crate clap;
use clap::{App, Arg};
// Define your enum
enum Vals {
Foo,
Bar,
Baz,
Qux
}
// Implement the trait
impl FromStr for Vals {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Foo" => Ok(Vals::Foo),
"Bar" => Ok(Vals::Bar),
"Baz" => Ok(Vals::Baz),
"Qux" => Ok(Vals::Qux),
_ => Err("no match")
}
}
}
fn main() {
// Create the application like normal
let enum_vals = ["Foo", "Bar", "Baz", "Qux"];
let m = App::new("myapp")
// Use a single positional argument that is required
.arg(Arg::from_usage("<type> 'The type to use'")
// Define the list of possible values
.possible_values(&enum_vals))
.get_matches();
let t = value_t_or_exit!(m.value_of("type"), Vals);
// Now we can use our enum like normal.
match t {
Vals::Foo => println!("Found a Foo"),
Vals::Bar => println!("Found a Bar"),
Vals::Baz => println!("Found a Baz"),
Vals::Qux => println!("Found a Qux")
}
}