HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

How can I access command line parameters in Rust?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howaccesslinerustcancommandparameters

Problem

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

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() {
    // we use nth(1) for the first argument because
    // nth(0) traditionally corresponds to the binary path
    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:

  • 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.

Code Snippets

use std::env;

fn main() {
    let args: Vec<_> = env::args().collect();
    if args.len() > 1 {
        println!("The first argument is {}", args[1]);
    }
}
use std::env;

fn main() {
    // we use nth(1) for the first argument because
    // nth(0) traditionally corresponds to the binary path
    if let Some(arg1) = env::args().nth(1) {
        println!("The first argument is {}", arg1);
    }
}

Context

Stack Overflow Q#15619320, score: 233

Revisions (0)

No revisions yet.