Matthew Maurer | 32e7669 | 2020-06-02 11:15:15 -0700 | [diff] [blame] | 1 | //! Somewhat complex example of usage of structopt. |
| 2 | |
| 3 | use structopt::StructOpt; |
| 4 | |
| 5 | #[derive(StructOpt, Debug)] |
| 6 | #[structopt(name = "example")] |
| 7 | /// An example of StructOpt usage. |
| 8 | struct Opt { |
| 9 | // A flag, true if used in the command line. |
| 10 | #[structopt(short, long)] |
| 11 | /// Activate debug mode |
| 12 | debug: bool, |
| 13 | |
| 14 | // An argument of type float, with a default value. |
| 15 | #[structopt(short, long, default_value = "42")] |
| 16 | /// Set speed |
| 17 | speed: f64, |
| 18 | |
| 19 | // Needed parameter, the first on the command line. |
| 20 | /// Input file |
| 21 | input: String, |
| 22 | |
| 23 | // An optional parameter, will be `None` if not present on the |
| 24 | // command line. |
| 25 | /// Output file, stdout if not present |
| 26 | output: Option<String>, |
| 27 | |
| 28 | // An optional parameter with optional value, will be `None` if |
| 29 | // not present on the command line, will be `Some(None)` if no |
| 30 | // argument is provided (i.e. `--log`) and will be |
| 31 | // `Some(Some(String))` if argument is provided (e.g. `--log |
| 32 | // log.txt`). |
| 33 | #[structopt(long)] |
| 34 | #[allow(clippy::option_option)] |
| 35 | /// Log file, stdout if no file, no logging if not present |
| 36 | log: Option<Option<String>>, |
| 37 | |
| 38 | // An optional list of values, will be `None` if not present on |
| 39 | // the command line, will be `Some(vec![])` if no argument is |
Joel Galenson | 108a00f | 2021-08-09 10:44:46 -0700 | [diff] [blame] | 40 | // provided (i.e. `--optv`) and will be `Some(Vec<String>)` if |
Matthew Maurer | 32e7669 | 2020-06-02 11:15:15 -0700 | [diff] [blame] | 41 | // argument list is provided (e.g. `--optv a b c`). |
| 42 | #[structopt(long)] |
| 43 | optv: Option<Vec<String>>, |
| 44 | |
| 45 | // Skipped option: it won't be parsed and will be filled with the |
| 46 | // default value for its type (in this case it'll be an empty string). |
| 47 | #[structopt(skip)] |
| 48 | skipped: String, |
| 49 | } |
| 50 | |
| 51 | fn main() { |
| 52 | let opt = Opt::from_args(); |
| 53 | println!("{:?}", opt); |
| 54 | } |