typestar

Validating arguments in Rust

clap can enforce ranges, enumerations and required combinations before main runs.

use clap::{Parser, ValueEnum};

#[derive(Copy, Clone, Debug, ValueEnum)]
enum Theme {
    Default,
    Monokai,
    Dracula,
}

#[derive(Parser, Debug)]
struct Cli {
    #[arg(long, value_parser = 1..=3)]
    stars: i64,

    #[arg(long, value_enum, default_value_t = Theme::Default)]
    theme: Theme,

    #[arg(long, requires = "output")]
    export: bool,

    #[arg(long)]
    output: Option<String>,
}

fn main() {
    let cli = Cli::parse();
    println!("{:?}", cli);
}

How it works

  1. value_parser with a range rejects out-of-bounds numbers.
  2. A ValueEnum restricts a flag to known values.
  3. requires and conflicts_with express the pairings.

Keywords and builtins used here

The run, in numbers

Lines
28
Characters to type
425
Tokens
89
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 53 seconds.

Type this snippet

Step 5 of 5 in Arguments, step 5 of 12 in CLI tools & HTTP clients.

← Previous Next →