Program arguments

Standard Library

The command line arguments can be accessed using std::env::args, which
returns an iterator that yields a String for each argument:

  1. use std::env;
  2. fn main() {
  3. let args: Vec<String> = env::args().collect();
  4. // The first argument is the path that was used to call the program.
  5. println!("My path is {}.", args[0]);
  6. // The rest of the arguments are the passed command line parameters.
  7. // Call the program like this:
  8. // $ ./args arg1 arg2
  9. println!("I got {:?} arguments: {:?}.", args.len() - 1, &args[1..]);
  10. }
  1. $ ./args 1 2 3
  2. My path is ./args.
  3. I got 3 arguments: ["1", "2", "3"].

Crates

Alternatively, there are numerous crates that can provide extra functionality
when creating command-line applications. The Rust Cookbook exhibits best
practices on how to use one of the more popular command line argument crates,
clap.