1 use std::path::PathBuf;
2 use std::ffi::OsStr;
3 
4 use pico_args::Arguments;
5 
6 #[derive(Debug)]
7 struct AppArgs {
8     help: bool,
9     number: u32,
10     opt_number: Option<u32>,
11     width: u32,
12     input: Option<PathBuf>,
13     free: Vec<String>,
14 }
15 
parse_width(s: &str) -> Result<u32, &'static str>16 fn parse_width(s: &str) -> Result<u32, &'static str> {
17     s.parse().map_err(|_| "not a number")
18 }
19 
parse_path(s: &OsStr) -> Result<PathBuf, &'static str>20 fn parse_path(s: &OsStr) -> Result<PathBuf, &'static str> {
21     Ok(s.into())
22 }
23 
main()24 fn main() {
25     if let Err(e) = submain() {
26         eprintln!("Error: {}.", e);
27     }
28 }
29 
submain() -> Result<(), pico_args::Error>30 fn submain() -> Result<(), pico_args::Error> {
31     let mut args = Arguments::from_env();
32     let args = AppArgs {
33         // Checks that optional flag is present.
34         help: args.contains(["-h", "--help"]),
35         // Parses a required value that implements `FromStr`.
36         // Returns an error if not present.
37         number: args.value_from_str("--number")?,
38         // Parses an optional value that implements `FromStr`.
39         opt_number: args.opt_value_from_str("--opt-number")?,
40         // Parses an optional value from `&str` using a specified function.
41         width: args.opt_value_from_fn("--width", parse_width)?.unwrap_or(10),
42         // Parses an optional value from `&OsStr` using a specified function.
43         input: args.opt_value_from_os_str("--input", parse_path)?,
44         // Will return all free arguments or an error if any flags are left.
45         free: args.free()?,
46     };
47 
48     println!("{:#?}", args);
49     Ok(())
50 }
51