clap/examples/13_enum_values.rs
Roland Fredenhagen 5580e8c465
ArgValue builder (#2758)
* feat(arg_value): ArgValue can be used for possible_values

Through the ArgValue it is possible:

* `hide` possible_values from showing in completion, help and validation
* add `about` to possible_values in completion

* Resolved a few change-requests by epage

* make clippy happy

* add ArgValue::get_visible_value

* remove verbose destructering

* rename ArgValue::get_hidden to ArgValue::is_hidden

* add test for help output of hidden ArgValues

* Documentation for ArgValue

There is an issue that required to implement From<&ArgValue> for
ArgValue. We should probably find a solution without that.

* fix requested changes by epage

* fix formatting

* add deref in possible_values call to remove From<&&str>

* make clippy happy

* use copied() instad of map(|v|*v)

* Finishing up for merge, hopefully

* changes requested by pksunkara
2021-09-19 10:29:09 +00:00

54 lines
1.4 KiB
Rust

// 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
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 m = App::new("myapp")
// Use a single positional argument that is required
.arg(
Arg::from("<type> 'The type to use'")
// Define the list of possible values
.possible_values(["Foo", "Bar", "Baz", "Qux"]),
)
.get_matches();
// Note that you don't have to specify the type since rustc can infer it for you
let t = m.value_of_t("type").unwrap_or_else(|e| e.exit());
// 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"),
}
}