[Avg. reading time: 4 minutes]
Command Line Args
Command Line Arguments allow you to pass inputs to a Rust program at runtime.
CLI Arguments are passed to the program when it is invoked.
Example
cargo --version
Arguments are commonly used for:
- File paths
- Configuration values
- Flags and modes
- Runtime parameters
Accessing Arguments
Rust provides std::env::args().
- Returns an iterator of String
- First argument is always the executable path
use std::env; fn main(){ for (index,argument) in env::args().enumerate(){ println!("{},{}", index, argument) } }
cargo run Rachel 25
0 -> target/debug/project_name
1 -> Rachel
2 -> 25
Pick a specific argument
Using nth()
use std::env;
fn main() {
let second = env::args().nth(1);
println!("{:?}", second);
}
- nth(1) returns Option
- Safe because arguments may not exist
Using skip() + next()
let name = env::args().skip(1).next();
Proper Handling with Option
Never assume arguments exist.
use std::env;
fn main() {
let name = env::args().skip(1).next();
match name {
Some(n) => println!("Hello {n}"),
None => {
println!("Missing argument");
std::process::exit(1);
}
}
}
Why not panic!?
- CLI programs should fail gracefully
- Exit with non-zero status instead of crashing