Sub topic 2
Options and Flags
Assume you know basic Rust structs, enums, Option, Result, Cargo, and terminal conventions. This chapter uses clap 4 with its derive API.
Options and flags
An option accepts a value, while a flag represents a choice that is either enabled or disabled. Short names use one dash, such as -f; long names use two, such as --filter.
use clap::Parser;
use std::path::PathBuf;
#[derive(Parser, Debug)]
#[command(version, about = "Search a file")]
struct Cli {
/// File to search
path: PathBuf,
/// Only print matching lines
#[arg(short, long)]
filter: Option<String>,
/// Increase diagnostic detail (-v, -vv)
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
}The path field is a required positional argument. filter is an optional value. verbose counts repeated flags, so -vv produces 2.
| Command-line input | Rust field |
|---|---|
| `app file.txt --filter error -vv` | `path`, `filter`, and `verbose` |
Help and version output
The #[command(version, about)] attribute enables generated --version and --help output. about uses the struct's documentation comment unless you provide an explicit string. The version normally comes from the package version in Cargo.toml.
Parsing values into Rust types
clap parses text according to each field's type. Invalid input produces a usage error before main continues. You can add constraints with value_parser.
#[arg(
long,
default_value_t = 8080,
value_parser = clap::value_parser!(u16).range(1..=65535)
)]
port: u16,This rejects values outside the valid TCP port range.
Limiting values to a set of choices
Use ValueEnum when an argument must match a known set of names.
#[derive(Clone, Debug, clap::ValueEnum)]
enum Format {
Text,
Json,
}A field declared as #[arg(long, value_enum)] format: Format accepts --format text or --format json, but rejects other values.
Defaults and environment variables
Use default_value_t for a Rust default. Use env for a fallback environment variable.
#[arg(long, default_value_t = 8080)]
port: u16,
#[arg(long, env = "APP_TOKEN", hide_env_values = true)]
token: Option<String>,A command-line value takes precedence over the environment variable, which takes precedence over no value.
Exercise
What does -vv produce for a field using ArgAction::Count?
Show answer
It produces the typed value 2.