Sub topic 2
Adding clap to your project
This chapter assumes you can create a Cargo project, edit Cargo.toml, and read compiler errors. By the end you will have clap 4 installed with the right features and a program that builds and responds to --help.
Create the project
cargo new filegrep
cd filegrepAdd the dependency
You can run cargo add, or edit Cargo.toml by hand. Both give the same result.
cargo add clap --features derive,env[package]
name = "filegrep"
version = "0.1.0"
edition = "2021"
description = "Print lines of a file that contain a pattern"
[dependencies]
clap = { version = "4", features = ["derive", "env"] }The version "4" lets Cargo pick any 4.x release, so you get fixes without breaking changes. The description field matters later. The version and about settings in the next chapter read it, along with version, from this file.
Choose features
clap turns on a set of default features, which cover help output, usage lines, colored output, error messages, and "did you mean" suggestions. Two features you will use in this tutorial are off by default.
| Feature | What it enables | Needed for |
|---|---|---|
| `derive` | `#[derive(Parser)]` and the related macros | Defining a CLI from a struct |
| `env` | `env = "NAME"` on an argument | Falling back to environment variables |
Features that you don't need stay out of your build, which keeps compile times lower.
Add clap_complete later
Shell completions live in a separate crate, clap_complete. You don't need it yet. When you reach the completions chapter, add it with cargo add clap_complete.
Verify the setup
Replace src/main.rs with the smallest derived parser:
use clap::Parser;
/// Print lines of a file that contain a pattern.
#[derive(Parser)]
#[command(version, about)]
struct Cli {}
fn main() {
Cli::parse();
println!("arguments parsed");
}Run it three ways. The -- tells Cargo to pass everything after it to your program instead of reading it itself.
cargo run -- --help
cargo run -- --version
cargo run -- --bogusThe first two print the help text and filegrep 0.1.0. The third prints an "unexpected argument" error and exits with status 2. You wrote no code for any of this.
Common errors
unresolved import clap::Parser: Thederivefeature is missing. Add it to thefeatureslist.no method named env found: Theenvfeature is missing. This error appears only once you useenv = "..."on an argument.- Old syntax from tutorials: Code that uses
clap::App,#[clap(...)], orStructOpttargets clap 2 or 3. In clap 4, useCommandand#[command(...)]or#[arg(...)].
Exercise
You add clap = "4" with no features, write use clap::Parser;, and the build fails. Which feature fixes it, and what two other things does that feature let you write?
Show answer
The derive feature. It enables #[derive(Parser)] and also the Subcommand and ValueEnum derives, which later chapters use. Change the dependency to clap = { version = "4", features = ["derive"] }.