2015-04-16 17:31:50 +00:00
|
|
|
// 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,
|
2018-01-25 04:05:05 +00:00
|
|
|
Qux,
|
2015-04-16 17:31:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Implement the trait
|
2015-04-18 17:20:58 +00:00
|
|
|
impl FromStr for Vals {
|
|
|
|
type Err = &'static str;
|
2015-10-01 01:45:35 +00:00
|
|
|
|
2015-04-18 17:20:58 +00:00
|
|
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
2015-04-16 17:31:50 +00:00
|
|
|
match s {
|
|
|
|
"Foo" => Ok(Vals::Foo),
|
|
|
|
"Bar" => Ok(Vals::Bar),
|
|
|
|
"Baz" => Ok(Vals::Baz),
|
|
|
|
"Qux" => Ok(Vals::Qux),
|
2018-01-25 04:05:05 +00:00
|
|
|
_ => Err("no match"),
|
2015-04-16 17:31:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
// Create the application like normal
|
|
|
|
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
|
2016-01-27 22:22:34 +00:00
|
|
|
.possible_values(&["Foo", "Bar", "Baz", "Qux"]))
|
2015-04-16 17:31:50 +00:00
|
|
|
.get_matches();
|
|
|
|
|
2016-01-22 04:18:52 +00:00
|
|
|
let t = value_t!(m, "type", Vals).unwrap_or_else(|e| e.exit());
|
2015-04-16 17:31:50 +00:00
|
|
|
|
|
|
|
// 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"),
|
2018-01-25 04:05:05 +00:00
|
|
|
Vals::Qux => println!("Found a Qux"),
|
2015-04-16 17:31:50 +00:00
|
|
|
}
|
2016-01-21 06:48:30 +00:00
|
|
|
}
|