Expand description

A pathologically simple command line argument parser.

Most argument parsers are declarative: you tell them what to parse, and they do it.

This one provides you with a stream of options and values and lets you figure out the rest.


struct Args {
    thing: String,
    number: u32,
    shout: bool,

fn parse_args() -> Result<Args, lexopt::Error> {
    use lexopt::prelude::*;

    let mut thing = None;
    let mut number = 1;
    let mut shout = false;
    let mut parser = lexopt::Parser::from_env();
    while let Some(arg) = parser.next()? {
        match arg {
            Short('n') | Long("number") => {
                number = parser.value()?.parse()?;
            Long("shout") => {
                shout = true;
            Value(val) if thing.is_none() => {
                thing = Some(val.into_string()?);
            Long("help") => {
                println!("Usage: hello [-n|--number=NUM] [--shout] THING");
            _ => return Err(arg.unexpected()),

    Ok(Args {
        thing: thing.ok_or("missing argument THING")?,

fn main() -> Result<(), lexopt::Error> {
    let args = parse_args()?;
    let mut message = format!("Hello {}", args.thing);
    if args.shout {
        message = message.to_uppercase();
    for _ in 0..args.number {
        println!("{}", message);


A small prelude for processing arguments.


A parser for command line arguments.

An iterator for the remaining raw arguments, returned by Parser::raw_args.

An iterator for multiple option-arguments, returned by Parser::values.


A command line argument found by Parser, either an option or a positional argument.

An error during argument parsing.


An optional extension trait with methods for parsing OsStrings.