Rust Command Line Arguments
Command line tools accept instructions when they start. Typing copy report.txt backup.txt passes two extra words to the program, and the program decides what to do with them. Arguments work like the order slip handed to a chef: the slip tells the kitchen exactly what to prepare.
Reading Arguments
The function std::env::args returns an iterator over every word typed after the program name. The collect method gathers them into a vector.
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
println!("{:?}", args);
}Run the program with cargo run -- apple banana. The double dash separates Cargo's own options from the arguments meant for your program.
["target/debug/demo", "apple", "banana"]
index: 0 1 2
+----------------+--------+--------+
args | program path | apple | banana |
+----------------+--------+--------+
The first item is always the path to the program itself. Real arguments start at position 1.
Checking the Count
Users forget arguments. Check the length before reading positions, or the program panics on an invalid index.
use std::env;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!("Usage: {} <name>", args[0]);
process::exit(1);
}
println!("Hello, {}!", args[1]);
}The call process::exit(1) ends the program with a failure code. Scripts read that code to learn whether the tool succeeded. Zero means success, and any other number signals a problem.
Converting Arguments to Numbers
Arguments always arrive as text. Use parse to convert them, and report friendly errors.
use std::env;
use std::process;
fn main() {
let args: Vec<String> = env::args().skip(1).collect();
if args.len() != 2 {
eprintln!("Usage: add <number> <number>");
process::exit(1);
}
let a: f64 = args[0].parse().unwrap_or_else(|_| {
eprintln!("'{}' is not a number", args[0]);
process::exit(1);
});
let b: f64 = args[1].parse().unwrap_or_else(|_| {
eprintln!("'{}' is not a number", args[1]);
process::exit(1);
});
println!("{}", a + b);
}
$ cargo run -- 4 2.5 6.5
The skip(1) call discards the program path so that index 0 refers to the first real argument.
Flags and Options
Many tools use flags such as --verbose. A simple loop can recognize them.
use std::env;
fn main() {
let mut verbose = false;
let mut files = Vec::new();
for arg in env::args().skip(1) {
if arg == "--verbose" || arg == "-v" {
verbose = true;
} else {
files.push(arg);
}
}
if verbose {
println!("Processing {} file(s)", files.len());
}
for f in &files {
println!("File: {f}");
}
}Environment Variables
Environment variables carry settings into a program as well. The function env::var returns a Result.
use std::env;
fn main() {
let level = env::var("LOG_LEVEL").unwrap_or(String::from("info"));
println!("Log level: {level}");
}Choosing Between Sources
| Source | Best For |
|---|---|
| Arguments | Values that change on every run |
| Flags | Switching features on or off |
| Environment variables | Settings shared across many runs |
| Config files | Long lists of options |
Using the clap Crate
Hand-written parsing grows messy as options multiply. The clap crate generates parsing code, help text, and error messages from a struct definition.
use clap::Parser;
#[derive(Parser)]
struct Cli {
/// Name of the person to greet
name: String,
/// Number of greetings
#[arg(short, long, default_value_t = 1)]
count: u8,
}
fn main() {
let cli = Cli::parse();
for _ in 0..cli.count {
println!("Hello, {}!", cli.name);
}
}Add the crate with cargo add clap --features derive. The program now supports --help automatically.
command line text --> clap --> Cli { name, count } --> your logic
Designing Friendly Tools
- Print a usage line when arguments are missing.
- Send errors to standard error with
eprintln!. - Return a non-zero exit code on failure.
- Offer short and long flag names for common options.
Key Points
env::args()lists the program path followed by user arguments.- Validate the argument count before indexing.
- Convert text to numbers with
parseand handle failures. - Use
process::exitwith a code to signal success or failure. - Reach for
clapwhen a tool needs many options.
