Command Line Arguments in Rust

Command-line arguments are a common way to parameterize execution of programs. For example, cargo run -- arg1 arg2 uses arg1 and arg2 as arguments to the Rust program.

use std::env;

fn main() {
    // std::env::args() provides access to raw command-line
    // arguments. Note that the first value in this iterator
    // is the path to the program, and std::env::args().skip(1)
    // holds the arguments to the program.
    let args: Vec<String> = env::args().collect();
    let args_without_prog: Vec<String> = env::args().skip(1).collect();

    // You can get individual args with normal indexing.
    let arg = &args[3];

    println!("{:?}", args);
    println!("{:?}", args_without_prog);
    println!("{}", arg);
}

To experiment with command-line arguments it’s best to build a binary with cargo build first.

$ cargo build --release
$ ./target/release/command_line_arguments a b c d
["./target/release/command_line_arguments", "a", "b", "c", "d"]
["a", "b", "c", "d"]
c

Next we’ll look at more advanced command-line processing with flags.