Sub topic 8
Limiting values to a set of choices
This chapter assumes you can define a CLI with #[derive(Parser)], add options with #[arg(long)], and read the parsed fields from the struct. Here you will restrict an option to a fixed set of values using ValueEnum.
The problem with free-form strings
Suppose a task manager has a --priority option. If the field is a String, any text is accepted, and you must validate it yourself in main. The compiler cannot tell you when you forget a case.
An enum fixes both problems. The set of valid values is the set of variants, and match forces you to handle each one.
Deriving ValueEnum
ValueEnum is a derive macro that teaches clap to convert a command-line string into an enum variant. Each variant becomes one allowed value. Clap lowercases the variant name by default, so High is typed as high.
use clap::{Parser, ValueEnum};
#[derive(Parser, Debug)]
struct Cli {
/// Task title
title: String,
/// How urgent the task is
#[arg(long, value_enum, default_value_t = Priority::Normal)]
priority: Priority,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum Priority {
Low,
Normal,
High,
}
fn main() {
let cli = Cli::parse();
println!("add {:?} with priority {:?}", cli.title, cli.priority);
}Three details matter here:
#[arg(value_enum)]tells clap to use theValueEnumimplementation for this field.default_value_t = Priority::Normalsupplies a default of the enum type. This works because the enum implementsValueEnumandClone. Clap needsCloneandDebugon the enum.- The derive on the enum needs
CopyandCloneonly by convention in most programs.Cloneis the required one.
What the user sees
An invalid value is rejected before your code runs, and clap lists the choices:
$ app "write docs" --priority urgent
error: invalid value 'urgent' for '--priority <PRIORITY>'
[possible values: low, normal, high]The --help output also shows [possible values: low, normal, high] and marks the default. Shell completions use the same list, which is covered in a later chapter.
Customizing the names
Use #[value(...)] on a variant to change how it is spelled on the command line, add an alias, or hide it.
use clap::ValueEnum;
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum Format {
/// Plain text output
Text,
/// Machine-readable output
#[value(name = "json", alias = "js")]
Json,
}
fn main() {
println!("{:?}", Format::from_str("js", true));
}The doc comment on a variant becomes its description in the long help. The from_str call above is a method of ValueEnum, and its second argument says whether to ignore case. In a derived parser you can get that behavior with #[arg(value_enum, ignore_case = true)].
Common errors
- Forgetting
value_enumon the field. Without it, clap triesFromStrand the build fails because the enum does not implement it. - Using
default_value_twith an enum that lacksDebugorClone. The compiler reports a missing trait bound. - Expecting
Highto be typed asHigh. Users must typehighunless you enableignore_case.
Exercise
You have enum Mode { FastScan, FullScan } deriving ValueEnum. What must the user type to select FullScan, and what happens if they type full?
Show answer
They type full-scan, because variant names are converted to kebab-case. Typing full is rejected with an "invalid value" error that lists the possible values fast-scan and full-scan, unless you add #[value(alias = "full")] to that variant.