• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! How to parse `--foo=true --bar=false` and turn them into bool.
2 
3 use structopt::StructOpt;
4 
true_or_false(s: &str) -> Result<bool, &'static str>5 fn true_or_false(s: &str) -> Result<bool, &'static str> {
6     match s {
7         "true" => Ok(true),
8         "false" => Ok(false),
9         _ => Err("expected `true` or `false`"),
10     }
11 }
12 
13 #[derive(StructOpt, Debug, PartialEq)]
14 struct Opt {
15     // Default parser for `try_from_str` is FromStr::from_str.
16     // `impl FromStr for bool` parses `true` or `false` so this
17     // works as expected.
18     #[structopt(long, parse(try_from_str))]
19     foo: bool,
20 
21     // Of course, this could be done with an explicit parser function.
22     #[structopt(long, parse(try_from_str = true_or_false))]
23     bar: bool,
24 
25     // `bool` can be positional only with explicit `parse(...)` annotation
26     #[structopt(long, parse(try_from_str))]
27     boom: bool,
28 }
29 
main()30 fn main() {
31     assert_eq!(
32         Opt::from_iter(&["test", "--foo=true", "--bar=false", "true"]),
33         Opt {
34             foo: true,
35             bar: false,
36             boom: true
37         }
38     );
39     // no beauty, only truth and falseness
40     assert!(Opt::from_iter_safe(&["test", "--foo=beauty"]).is_err());
41 }
42