Command-line arguments refer to values or options passed to a program when executing it from the command line. These arguments allow users to customize program behavior at launch without modifying the source code.
Taking the cargo
command as an example, different functionalities can be executed by passing different arguments:
cargo new app1
cargo new --lib lib1
cargo run
cargo build
In Rust, command-line arguments can be accessed using the std::env::args()
function from the standard library:
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
//let argc = args.len(); // Argument count
//println!("{}",args[0]); // Program path (always present)
//println!("{}",args[1]); // First argument (if exists)
//println!("{}",args[2]); // Second argument (if exists)
// Iterate and print argument indices and values
for (index, value) in args.iter().enumerate() {
println!("{} => {}", index, value);
}
}
When using cargo run
, add --
to separate cargo's arguments from your program's arguments.
Program execution example:

For handling complex arguments, the clap
library is recommended.