How can I access command line parameters?

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?


Solution 1:

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 Strings (that are easy to work with) but panics if one of the arguments is not valid unicode. The latter iterates over OsStrings 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:

  • docopt: you just write the help message, and the parsing code is generated for you.
  • clap: you describe the options you want to parse using a fluent API. Faster than docopt and gives you more control.
  • getopts: port of the popular C library. Lower-level and even more control.
  • structopt: built on top of clap, it is even more ergonomic to use.

Solution 2:

Docopt is also available for Rust, which generates a parser for you from a usage string. As a bonus in Rust, a macro can be used to automatically generate the struct and do type based decoding:

docopt!(Args, "
Usage: cp [-a] SOURCE DEST
       cp [-a] SOURCE... DIR

Options:
    -a, --archive  Copy everything.
")

And you can get the arguments with:

let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());

The README and documentation have plenty of full working examples.

Disclaimer: I am one of the authors of this library.

Solution 3:

Rust has getopt-style CLI argument parsing in the getopts crate.