Clap Notes
1. Introduction to Clap
Clap is a Rust library for parsing command-line arguments. It provides an easy-to-use API for defining arguments, options, flags, and subcommands.
2. Adding Clap to Your Project
Add the following to Cargo.toml
:
3. Basic Usage
use clap::Parser;
#[derive(Parser)]
struct Args {
#[arg(short, long)]
name: String,
}
fn main() {
let args = Args::parse();
println!("Hello, {}!", args.name);
}
Running
Output
4. Flags and Options
use clap::Parser;
#[derive(Parser)]
struct Args {
#[arg(short, long)]
verbose: bool,
}
fn main() {
let args = Args::parse();
if args.verbose {
println!("Verbose mode enabled");
}
}
Running
Output
5. Default Values
use clap::Parser;
#[derive(Parser)]
struct Args {
#[arg(short, long, default_value_t = 10)]
count: u32,
}
fn main() {
let args = Args::parse();
println!("Count: {}", args.count);
}
6. Subcommands
use clap::{Parser, Subcommand};
#[derive(Parser)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
Add { value: i32 },
Remove { value: i32 },
}
fn main() {
let cli = Cli::parse();
match cli.command {
Commands::Add { value } => println!("Adding: {}", value),
Commands::Remove { value } => println!("Removing: {}", value),
}
}
Running
7. Validating Input
use clap::Parser;
#[derive(Parser)]
struct Args {
#[arg(short, long, value_parser = clap::value_parser!(u32).range(1..=100))]
percentage: u32,
}
fn main() {
let args = Args::parse();
println!("Percentage: {}", args.percentage);
}
8. Environment Variable Support
use clap::Parser;
#[derive(Parser)]
struct Args {
#[arg(short, long, env = "USER_NAME")]
name: String,
}
fn main() {
let args = Args::parse();
println!("Hello, {}!", args.name);
}
Running
Output
9. Help and Version Auto-Generation
Clap automatically generates help and version messages.
use clap::Parser;
#[derive(Parser)]
#[command(version = "1.0", about = "Example CLI tool")]
struct Args {}
fn main() {
let _args = Args::parse();
}