The Rust tutorial does not explain how to take parameters from the command line. fn main()
is only shown with an empty parameter list in all examples.
What is the correct way of accessing command line parameters from main
?
You can access the command line arguments by using the std::env::args
or std::env::args_os
functions. Both functions return an iterator over the arguments. The former iterates over String
s (that are easy to work with) but panics if one of the arguments is not valid unicode. The latter iterates over OsString
s and never panics.
Note that the first element of the iterator is the name of the program itself (this is a convention in all major OSes), so the first argument is actually the second iterated element.
An easy way to deal with the result of args
is to convert it to a Vec
:
use std::env;
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() > 1 {
println!("The first argument is {}", args[1]);
}
}
You can use the whole standard iterator toolbox to work with these arguments. For example, to retrieve only the first argument:
use std::env;
fn main() {
if let Some(arg1) = env::args().nth(1) {
println!("The first argument is {}", arg1);
}
}
You can find libraries on crates.io for parsing command line arguments: