clap::value_t! [] [src]

macro_rules! value_t {
    ($m:ident.value_of($v:expr), $t:ty) => {
        match $m.value_of($v) {
            Some(v) => {
                match v.parse::<$t>() {
                    Ok(val) => Ok(val),
                    Err(_)  => Err(format!("'{}' isn't a valid value", ::clap::Format::Warning(v))),
                }
            },
            None => Err(format!("The argument '{}' not found", ::clap::Format::Warning($v)))
        }
    };
    ($m:ident.values_of($v:expr), $t:ty) => {
        match $m.values_of($v) {
            Some(ref v) => {
                let mut tmp = Vec::with_capacity(v.len());
                let mut err = None;
                for pv in v {
                    match pv.parse::<$t>() {
                        Ok(rv) => tmp.push(rv),
                        Err(e) => {
                            err = Some(format!("'{}' isn't a valid value\n\t{}", ::clap::Format::Warning(pv),e));
                            break
                        }
                    }
                }
                match err {
                    Some(e) => Err(e),
                    None => Ok(tmp)
                }
            },
            None => Err(format!("The argument '{}' was not found", ::clap::Format::Warning($v)))
        }
    };
}

Convenience macro getting a typed value T where T implements std::str::FromStr This macro returns a Result<T,String> which allows you as the developer to decide what you'd like to do on a failed parse. There are two types of errors, parse failures and those where the argument wasn't present (such as a non-required argument).

You can use it to get a single value, or a Vec<T> with the values_of()

NOTE: Be cautious, as since this a macro invocation it's not exactly like standard syntax.

Example single value

let matches = App::new("myapp")
              .arg_from_usage("[length] 'Set the length to use as a pos whole num, i.e. 20'")
              .get_matches();
let len = value_t!(matches.value_of("length"), u32)
                .unwrap_or_else(|e|{
                    println!("{}",e);
                    std::process::exit(1)
                });

println!("{} + 2: {}", len, len + 2);

Example multiple values

let matches = App::new("myapp")
              .arg_from_usage("[seq]... 'A sequence of pos whole nums, i.e. 20 45'")
              .get_matches();
for v in value_t!(matches.values_of("seq"), u32)
            .unwrap_or_else(|e|{
                println!("{}",e);
                std::process::exit(1)
            }) {
    println!("{} + 2: {}", v, v + 2);
}