aboutsummaryrefslogtreecommitdiff
path: root/clap/examples/13b_enum_values_manual.rs
blob: 81ffe5ebdcd8e628ac2ee9f6d2ddb579cf9a2b69 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 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 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(&["Foo", "Bar", "Baz", "Qux"]))
                    .get_matches();

    let t = value_t!(m, "type", Vals).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")
    }
}