]> git.proxmox.com Git - rustc.git/blob - vendor/structopt/examples/keyvalue.rs
New upstream version 1.62.1+dfsg1
[rustc.git] / vendor / structopt / examples / keyvalue.rs
1 //! How to parse "key=value" pairs with structopt.
2
3 use std::error::Error;
4 use structopt::StructOpt;
5
6 /// Parse a single key-value pair
7 fn parse_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn Error>>
8 where
9 T: std::str::FromStr,
10 T::Err: Error + 'static,
11 U: std::str::FromStr,
12 U::Err: Error + 'static,
13 {
14 let pos = s
15 .find('=')
16 .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{}`", s))?;
17 Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
18 }
19
20 #[derive(StructOpt, Debug)]
21 struct Opt {
22 // number_of_values = 1 forces the user to repeat the -D option for each key-value pair:
23 // my_program -D a=1 -D b=2
24 // Without number_of_values = 1 you can do:
25 // my_program -D a=1 b=2
26 // but this makes adding an argument after the values impossible:
27 // my_program -D a=1 -D b=2 my_input_file
28 // becomes invalid.
29 #[structopt(short = "D", parse(try_from_str = parse_key_val), number_of_values = 1)]
30 defines: Vec<(String, i32)>,
31 }
32
33 fn main() {
34 let opt = Opt::from_args();
35 println!("{:?}", opt);
36 }