Method lrs::getopt::Getopt::new

Creates a new parser.

Syntax

impl<'a, I> Getopt<'a, I>
    where I: Iterator<Item = &'static CStr>,
{
    fn new(args: I, opts: &'a [(Option<char>, Option<&'static str>, bool)]) -> Getopt<'a, I>
}

Arguments

NameDescription
args

An iterator over the command line arguments.

opts

The arguments that take (optional) parameters.

Remarks

The args argument should start at the first real argument, not at the program name. See the example below.

The opts argument has the following structure: (short name, long name, optional). The short name is the character used for parsing of POSIX-style (-a) options. The long name is the string used for parsing GNU-style (--argument) options. The short name must be in the ASCII set. The optional parameter defines whether the parameter of this argument is optional.

The opts argument should thus only contain those arguments that take an (optional) parameter.

The parsing proceeds as follows:

Examples

The following example contains the code for parsing argument of a program with the following help message:

Usage: my_program [OPTIONS]*

Options:
  -a, --arg[=PARAMETER]
  -b PARAMETER
      --something-else
  -c

The code:

let mut args = env::args();
args.next(); // skip program name

let params = [
    (Some('a'), Some("arg"), true),
    (Some('b'), None, false),
];

for (arg, param) in Getopt::new(args, &params) {
    match arg.as_ref() {
        b"a" | b"arg" => {
            if let Some(param) = param {
                // ...
            } else {
                // ...
            }
        },
        b"b" => {
            if let Some(param) = param {
                // ...
            } else {
                // errer: missing parameter
            }
        },
        b"something-else" => {
            // ...
        }
        b"c" => {
            // ...
        }
        arg => {
            // error: unexpected argument
        }
    }
}

This program can be invoked as follows:

my_program -c
my_program -cc
my_program --something-else -c
my_program -cbPARAMETER
my_program -cb PARAMETER
my_program b PARAMETER
my_program --arg=PARAMETER
my_program -aPARAMETER