You can access the command line arguments passed to your program using the std::env::args()
function. This returns an Args
iterator which you can loop over or collect into a Vec
.
Iterating Through Arguments
use std::env;
fn main() {
for argument in env::args() {
if argument == "--help" {
println!("You passed --help as one of the arguments!");
}
}
}
Collecting into a Vec
use std::env;
fn main() {
let arguments: Vec<String> = env::args().collect();
println!("{} arguments passed", arguments.len());
}
You might get more arguments than you expect if you call your program like this:
./example
Although it looks like no arguments were passed, the first argument is (usually) the name of the executable. This isn't a guarantee though, so you should always validate and filter the arguments you get.