Sub topic 8
Limiting values to a set of choices
Why restrict values
A String field accepts any text. If your tool supports only three output formats, a typo like --format jsno reaches your own code, and you must check for it by hand. A restricted argument moves that check into clap. Clap rejects bad input before main continues, prints the allowed values, and exits with a non-zero status.
This chapter assumes you know how options and typed values work from the earlier chapters. It covers the ValueEnum derive, how to rename and document choices, and when a plain string list is a better fit.
Deriving ValueEnum
ValueEnum is a derive macro for enums whose variants have no fields. Each variant becomes one accepted value. You attach the enum to an argument with value_enum.
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();
let marker = match cli.priority {
Priority::Low => "-",
Priority::Normal => "*",
Priority::High => "!",
};
println!("[{marker}] {}", cli.title);
}Running app "Pay rent" --priority high prints [!] Pay rent. The field has type Priority, not String, so match is checked for exhaustiveness. If you add a Critical variant later, the compiler flags every match that ignores it.
Three details are worth knowing:
value_enumis required on the argument. Without it clap treats the field as an ordinary value and fails to compile unlessPriorityimplementsFromStrandClone.Cloneis required because clap stores parsed values internally and clones them out.Copyis optional, but it is convenient for small enums.default_value_t = Priority::Normalworks withoutDisplay. Clap asks theValueEnumimplementation for the variant's name and shows it as[default: normal]in the help.
What clap does with the input
For an invalid value, the error looks like this:
error: invalid value 'urgent' for '--priority <PRIORITY>'
[possible values: low, normal, high]
For more information, try '--help'.Clap writes this to stderr and exits with code 2. Your program never sees the bad value. The exact wording can vary slightly between clap 4 releases, and clap may add a "did you mean" tip when the input is close to a valid name.
The --help output includes the same list on the argument's line, as [default: normal] [possible values: low, normal, high].
Naming, aliases, and documentation
By default, clap converts variant names to kebab-case. PlainText becomes plain-text, and High becomes high. The #[value(...)] attribute on a variant changes this.
| Attribute | Effect |
|---|---|
| `#[value(name = "txt")]` | Replaces the generated name. |
| `#[value(alias = "grid")]` | Accepts an extra spelling. Aliases are not shown in the possible-values list. |
| `#[value(alias = "a", alias = "b")]` | Accepts several extra spellings. |
| `#[value(hide = true)]` | Accepts the value but leaves it out of help and error messages. |
| `#[value(skip)]` | Removes the variant from the CLI entirely. |
Doc comments on variants become the help text for each value. When any variant has one, --help switches from the one-line list to a per-value description.
The next program uses these attributes. It also sets ignore_case on the argument, adds a flag that prints the available formats, and includes a test module.
use clap::{Parser, ValueEnum};
#[derive(Parser, Debug)]
struct Cli {
/// Output format
#[arg(short, long, value_enum, ignore_case = true, default_value_t = Format::Table)]
format: Format,
/// Print the accepted formats and exit
#[arg(long)]
list_formats: bool,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum Format {
/// Machine-readable JSON
Json,
/// Aligned columns for terminals
#[value(alias = "grid")]
Table,
/// Plain text, one record per line
#[value(name = "txt")]
PlainText,
}
fn main() {
let cli = Cli::parse();
if cli.list_formats {
for variant in Format::value_variants() {
let value = variant.to_possible_value().expect("no variant is skipped");
println!("{}", value.get_name());
}
return;
}
println!("using format {:?}", cli.format);
}
#[cfg(test)]
mod tests {
use super::*;
use clap::error::ErrorKind;
#[test]
fn accepts_alias_and_any_case() {
let cli = Cli::try_parse_from(["app", "--format", "GRID"]).unwrap();
assert_eq!(cli.format, Format::Table);
}
#[test]
fn rejects_unknown_format() {
let err = Cli::try_parse_from(["app", "--format", "xml"]).unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidValue);
}
#[test]
fn renamed_value_replaces_generated_name() {
assert!(Cli::try_parse_from(["app", "--format", "txt"]).is_ok());
assert!(Cli::try_parse_from(["app", "--format", "plain-text"]).is_err());
}
}Format::value_variants() and to_possible_value() come from the ValueEnum trait. They let you list the choices in your own output, such as a formats subcommand, without a second hand-written list that can drift out of date. Add #[value(skip)] to a variant and to_possible_value returns None for it, so the expect above would panic. Handle that case if you use skip.
Parsing the name yourself
ValueEnum also provides from_str(input, ignore_case), which returns Result<Self, String>. It is useful when the value comes from somewhere other than the command line, such as a config file or an environment variable you read yourself:
use clap::ValueEnum;
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum Level {
Info,
Debug,
}
fn main() {
println!("{:?}", Level::from_str("debug", false));
println!("{:?}", Level::from_str("DEBUG", true));
println!("{:?}", Level::from_str("trace", false).is_err());
}This prints Ok(Debug), Ok(Debug), and true. The names it accepts are the same as on the command line, so both paths stay consistent.
Repeated and multiple values
An enum works inside Vec and Option like any other typed value. With Vec<Format> and value_enum, each occurrence of --format adds one element:
use clap::{Parser, ValueEnum};
#[derive(Parser, Debug)]
struct Cli {
/// Formats to write, repeat the flag for more than one
#[arg(long = "format", value_enum)]
formats: Vec<Format>,
}
#[derive(Copy, Clone, Debug, ValueEnum)]
enum Format {
Json,
Yaml,
}
fn main() {
let cli = Cli::parse();
println!("{:?}", cli.formats);
}app --format json --format yaml prints [Json, Yaml]. With no --format, the vector is empty, which is not an error. Use required = true if at least one is mandatory.
When a string list is enough
If you only need a quick check and never branch on the value, clap accepts a list of strings as the parser:
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
#[arg(long, value_parser = ["json", "yaml"], default_value = "json")]
format: String,
}
fn main() {
let cli = Cli::parse();
println!("{}", cli.format);
}Clap rejects anything outside the list with the same style of error. The trade-off is that the field is still a String. Your match needs a catch-all arm for values the compiler cannot know are impossible, and the value list lives in an attribute instead of a type. Prefer ValueEnum when the choice controls program behavior. Use the string list for pass-through values, such as a name you forward to another tool.
Common mistakes
- Forgetting
value_enum. The derive on the enum alone does nothing for the field. Addvalue_enumto the#[arg(...)]attribute. - Expecting aliases in help. Aliases are accepted silently. If users should discover a spelling, make it a real variant name or document it.
- Using
Displayfor the default. You do not need it. Pass the variant todefault_value_tand clap reads its name throughValueEnum. - Renaming a variant and breaking scripts. The value names are part of your CLI's public interface. Changing
TabletoGridbreaks every script that passestable. Keep the old name as an alias. - Combining
skipwithto_possible_value().unwrap(). Skipped variants returnNone.
Exercise
A Mode enum has variants Fast, SafeMode, and Debug. You want users to type fast, safe, or debug, and you want quick to also work for fast without appearing in the help. Which attributes do you put on the variants, and what does a user see if they type --mode SAFE?
Show answer
Put #[value(alias = "quick")] on Fast, #[value(name = "safe")] on SafeMode (the default name would be safe-mode), and leave Debug alone. Aliases do not appear in help or error output, so quick stays hidden. --mode SAFE is rejected with an invalid-value error that lists fast, safe, debug and exits with code 2, because ignore_case = true was not set on the argument. Adding ignore_case = true to the #[arg(...)] makes SAFE match safe.
Exercise
Why does Cli::try_parse_from(["app", "--format", "xml"]).unwrap_err().kind() return ErrorKind::InvalidValue in the test above, instead of the test panicking inside the parser?
Show answer
try_parse_from returns a Result and never exits the process. It reports the failure as a clap::Error. kind() identifies the category, and InvalidValue means the text did not match any accepted value. Cli::parse() handles the same error by printing it to stderr and exiting with code 2.