Sub topic 1
What a Command-Line Interface Is Made Of
Prerequisites
Assume you know Rust structs, Option, Result, Cargo, and basic terminal commands. This chapter uses clap 4 and its derive API.
What a command-line interface is made of
A command-line interface (CLI) is a program controlled by text typed in a terminal. The shell passes the program a list of strings. A CLI parser gives those strings meaning and converts them into Rust values.
| Part | Example | Meaning |
|---|---|---|
| Positional argument | `notes.txt` | Value identified by its position |
| Option | `--filter error` | Named setting with a value |
| Flag | `--verbose` | Named on/off setting |
| Subcommand | `git commit` | Selects an operation |
Adding clap to your project
From a Cargo project, add clap with its derive feature:
[dependencies]
clap = { version = "4", features = ["derive"] }The derive feature enables Rust attributes such as #[derive(Parser)]. Cargo downloads the crate and compiles it when you run cargo build.
Your first CLI with `#[derive(Parser)]`
Parser is a trait that turns a struct definition into a command-line parser. Attributes describe the command and its arguments. Cli::parse() reads the process arguments and returns a populated Cli value.
use clap::Parser;
use std::path::PathBuf;
#[derive(Parser, Debug)]
#[command(version, about = "Search a file")]
struct Cli {
/// File to search
path: PathBuf,
}
fn main() {
let cli = Cli::parse();
println!("searching {}", cli.path.display());
}The doc comment becomes help text. version and about let clap generate standard help and version behavior.
Positional arguments
The path field is positional because it has no #[arg] attribute. Its position determines its meaning. Because it is a plain PathBuf, the argument is required. Running the program without a path produces a parser error and a non-success exit status.
A field such as Option<PathBuf> would make the value optional. Use the type to express whether a value must exist, then use attributes for names and validation.
Exercise
What does PathBuf communicate about the path argument?
Show answer
It tells clap to parse the argument as a filesystem path and gives the program an owned, typed path value.