clap Basics
Argument parsing.
clap Basics is a free Learn Rust Coding lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why clap?
clap (Command Line Argument Parser) is the de-facto standard crate for building CLIs in Rust.
- Parses arguments, flags, and options
- Generates
--helpand--versionautomatically - Validates input and reports friendly errors
Without it you would manually iterate over std::env::args() and handle every edge case yourself.
Reading args by hand
Before reaching for clap, it helps to see the raw approach. std::env::args() yields an iterator where the first item is the program name.
fn main() {
let args: Vec<String> = std::env::args().collect();
println!("Program: {}", args[0]);
println!("Got {} extra arg(s)", args.len() - 1);
}Adding clap to Cargo.toml
To use clap you declare it as a dependency. The derive feature unlocks the macro-based API.
cargo add clap --features derive
This step runs in your terminal and edits your project files, so it is not something we execute here.
[dependencies]
clap = { version = "4", features = ["derive"] }The builder API
clap has two styles. The builder API constructs a Command at runtime by chaining method calls.
use clap::{Command, Arg};
fn main() {
let cmd = Command::new("greet")
.arg(Arg::new("name"));
let matches = cmd.get_matches();
// access values from matches
}Positional arguments
A positional argument is supplied by order, not by a flag. Here name is read directly from the command line.
greet Alicesets name to Alice
use clap::{Command, Arg};
fn main() {
let m = Command::new("greet")
.arg(Arg::new("name").required(true))
.get_matches();
let name = m.get_one::<String>("name").unwrap();
println!("Hello, {}!", name);
}Optional flags
A flag is a boolean switch. Use ArgAction::SetTrue so its presence flips a bool.
--loudturns the flag on
use clap::{Command, Arg, ArgAction};
fn main() {
let m = Command::new("greet")
.arg(Arg::new("loud").long("loud").action(ArgAction::SetTrue))
.get_matches();
let loud = m.get_flag("loud");
println!("loud = {}", loud);
}Options with values
An option takes a value, like --count 3. Give it a short and a long name for ergonomics.
use clap::{Command, Arg};
fn main() {
let m = Command::new("greet")
.arg(Arg::new("count").short('c').long("count"))
.get_matches();
if let Some(c) = m.get_one::<String>("count") {
println!("count = {}", c);
}
}Default values
Give an argument a fallback with default_value so users can omit it.
- If
--countis missing, it becomes 1
use clap::{Command, Arg};
fn main() {
let m = Command::new("greet")
.arg(Arg::new("count").long("count").default_value("1"))
.get_matches();
let count = m.get_one::<String>("count").unwrap();
println!("count = {}", count);
}Simulating the result
Even without clap installed we can model what the parsed values look like. Here is a plain-Rust stand-in showing the logic clap performs for us.
fn main() {
let name = "Alice";
let count: u32 = 3;
for _ in 0..count {
println!("Hello, {}!", name);
}
}Auto-generated help
clap builds --help for free from your argument metadata. Add about and help strings to make it useful.
use clap::{Command, Arg};
fn main() {
Command::new("greet")
.about("Greets a person")
.arg(Arg::new("name").help("Who to greet"))
.get_matches();
}Version flag
Set a version once and clap wires up --version. The crate_version! macro pulls it from Cargo.toml.
use clap::Command;
fn main() {
Command::new("greet")
.version("1.0.0")
.get_matches();
}Quick Check
Test your understanding of clap basics.
Recap
You learned the foundations of clap:
- Add it with the
derivefeature - The builder API uses
CommandandArg - Positionals are ordered; flags use
SetTrue; options take values default_valueprovides fallbacks--helpand--versionare generated automatically
Next you will structure larger CLIs with subcommands.
Frequently asked questions
Is the “clap Basics” lesson free?
Yes — the full text of “clap Basics” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “clap Basics”?
Argument parsing. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “clap Basics” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- clap Basics
- Subcommands
- Derive API
- Validation and Help