Fundamentos do clap
Análise de argumentos
Fundamentos do clap é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Learn Rust Coding, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Learn Rust Coding inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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.
Perguntas Frequentes
A aula “Fundamentos do clap” é grátis?
Sim — o texto completo de “Fundamentos do clap” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Learn Rust Coding, atualize para CoddyKit PRO. O curso de Learn Rust Coding inclui 4 aulas no total.
O que vou aprender em “Fundamentos do clap”?
Análise de argumentos Você pratica Learn Rust Coding com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Learn Rust Coding?
Nenhuma experiência prévia é necessária. Learn Rust Coding no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.
Quanto tempo leva a aula “Fundamentos do clap”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Learn Rust Coding?
Sim. Cada aula de Learn Rust Coding inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Fundamentos do clap
- Subcomandos
- API de derivação
- Validação e ajuda