Command Line Arguments
The command line arguments module is not part of the standard set. We need to include the module:
use std::env;
We now have access to the
env::args();
functions.
This function returns an iterator. So we need to enumerate the values to access them. The first value in the iterator, is always the path to the executable running.
Since the env::args()
function returns an iterator, we need to enumerate the values, to access them:
for (item, index) in env::args().enumerate() {
println!("{}", item);
}
Cool huh. When you run the program. Dropping flags into the program is done thusly:
$ cargo run arg1 arg2 arg3
The env::args() function will then line up the flags, whatever the may be. If we're reading the values once the get into the program, don't forget to define their datatype if they are being read into variables. They will be read into program as strings.
The env module also contains a function called nth(), which allows you to access a specific argument from the values passed into the program. So, to access the second argument passsed into the program:
let input_2 = env::args().nth(2).unwrap();
Notice we need to call the rustunwrap() function here too. Probably because the args() function returns an iterator, which presumably needs some further processing to extract the value.
When handling command line arguments, an incorrect number of arguments will cause a runtime error. So we must safeguard against this with an rustif
statement when the program first runs:
if env::args().len() < 2 {
println!("This program requires at least 2 arguments");
return false;
}
Written by Thomas,