Sub topic 3
Conflicts, Requirements, and Groups
Assume you know basic Rust, Cargo, Option, Result, and clap’s derive API. This chapter connects argument validation with larger CLI design.
Validate related arguments
Use conflicts_with when two arguments cannot appear together. Use requires when one argument needs another. An ArgGroup expresses a choice, such as requiring exactly one output format.
use clap::{ArgGroup, Parser, Subcommand};
#[derive(Parser, Debug)]
#[command(group(
ArgGroup::new("format")
.required(true)
.args(["json", "text"])
))]
struct Cli {
#[arg(long, conflicts_with = "verbose")]
quiet: bool,
#[arg(long)]
verbose: bool,
#[arg(long, group = "format")]
json: bool,
#[arg(long, group = "format")]
text: bool,
#[arg(long, requires = "json")]
pretty: bool,
#[arg(long, global = true)]
config: Option<String>,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
List,
Remove { id: u32 },
}clap checks these relationships while parsing. Your application receives a valid combination or never starts its main logic.
| Rule | Example | Purpose |
|---|---|---|
| Conflict | `--quiet` conflicts with `--verbose` | Reject incompatible choices |
| Requirement | `--pretty` requires `--json` | Enforce a dependency |
| Group | `--json` or `--text` | Require or limit a set of arguments |
A global argument, such as --config, can appear before or after the subcommand. Each Subcommand variant owns the arguments for one operation.
Handle errors and separate logic
Cli::parse() prints clap-generated errors and exits with a failure code. Business errors should be returned by a separate function and printed to standard error.
fn run(cli: &Cli) -> Result<(), String> {
if let Commands::Remove { id } = cli.command {
if id == 0 {
return Err("id must be greater than zero".into());
}
}
Ok(())
}Keep parsing thin. This makes run reusable and easy to test.
Test, complete, and choose an API
Use try_parse_from to test without starting a process. CommandFactory::debug_assert() catches invalid CLI definitions.
Shell completions can be generated with clap_complete from Cli::command(), keeping completion names synchronized with parsing.
Choose the derive API for a mostly static CLI. Choose the builder API when arguments are assembled dynamically or when runtime configuration controls the command definition. The builder API uses Command, Arg, and ArgMatches, but requires more manual string-based wiring.
Exercise
Which clap feature should model a required choice between --json and --text?
Show answer
Use an ArgGroup with .required(true) and add both argument names to the group.