How to access command line parameters?

shutefan picture shutefan · Mar 25, 2013 · Viewed 43.8k times · Source

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?

Answer

barjak picture barjak · Mar 25, 2013

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.