Home > Articles

Getting Started

This chapter is from the book

This chapter is from the book

Command-Line Arguments

Command-line arguments are sometimes used to affect application initialization, configuration, or flow control. This is an often-used technique to receive direction from a user. Entered at the command line, the arguments form a zero-based collection of values. The full path of the application itself is usually provided as the first command-line argument. The details about command-line arguments may vary between different environments. Be sure to review the specific documentation for a particular operating system.

The following command line has three arguments:

     myapp arg1 arg2

For the cargo run command, append the command-line arguments. The first argument, which is the full name of the application, is set implicitly. Therefore, arg1 and arg2 of this example are actually the second and third command-line arguments from perspective of the application:

cargo run arg1 arg2

Command-line arguments are provided as input to the main function in many languages. However, the main function in Rust has no parameters. Command-line arguments are instead read programmatically using the std::env::args function, which is found in the std::env module. The args function returns an iterator to the sequence of command-line arguments. Furthermore, iterator functions, such as the nth and collect functions, are available to access the command-line arguments. The nth function returns a specific command-line argument, if available. The collect function returns the arguments as a collection.

Listing 2.13 demonstrates various ways to access the command-line arguments.

Code Listing 2.13. Various approaches to accessing command-line arguments

fn main() {
    // display arg 0
    if let Some(arg)=std::env::args().nth(0) {
        println!("{}", arg);
    }

    // iterate and display args
    for arg in std::env::args() {
        println!("{}", arg);
    }

   // collect and display args
    let all_arg: String=std::env::args().collect();
    println!("{}", all_arg);
}

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.