expression
Clap ValueEnum: restrict choices
A value enum represents a finite set of supported modes. Clap validates text before returning the typed value. This report tool offers text or CSV; the example chooses CSV without writing a file. Uses a fixed synthetic argument list or local data. Expected stdout (not executed): format: csv Common mistake: Accepting arbitrary format strings and failing much later in the program.
Formal Syntax & Structure
rust syntaxrust
#[derive(clap::ValueEnum, Clone)]Working Example
Example Snippetrust
fn main() { use clap::{Parser, ValueEnum}; #[derive(Clone, ValueEnum)] enum Format { Text, Csv } #[derive(Parser)] struct Cli { #[arg(long, value_enum)] format: Format } let cli = Cli::try_parse_from(["report", "--format", "csv"]).unwrap(); assert!(Cli::try_parse_from(["report", "--format", "unknown"]).is_err()); println!("format: {}", match cli.format { Format::Text => "text", Format::Csv => "csv" });}