liveBook · Manning

Command-line argument

As explained in Learn Rust in a Month of Lunches

A command-line argument is a value supplied to a program when it is launched through a command-line interface.

A command-line argument is input supplied when a program starts. Unlike keyboard input read while the program is running, it is already available at launch. In Rust, `std::env::args()` provides these inputs as strings. section 18.2 section 18.2.2

The first entry is always the program name, even when the user supplies nothing else. Because `Args` can be iterated over, a loop can print each entry. Use `.skip(1)` when you want only the words the user added. section 18.2.2

use std::env::args;
 
fn main() {
    let input = args();
    input.skip(1).for_each(|item| {
        println!(
            "You wrote {item}, which in capital letters is {}",
            item.to_uppercase()
        );
    })
} 

This example skips the program name, then prints each remaining argument alongside an uppercase version. section 18.2.2

Use an argument as an instruction

A program can check the first user-supplied word for `capital` or `lowercase`, then print the following words in that form. For example, `cargo run capital I think I understand now` produces uppercase words. If the instruction is unrecognized, the example leaves the following words unchanged. section 18.2.2

Arguments are values passed on the command line; environment variables instead concern overall configuration. A familiar command-line argument is `--open` in `cargo doc --open`. section 18.5

How Learn Rust in a Month of Lunches covers it

How deep it goes
Works through printing, skipping, and matching arguments in a small program.
Examples
Shows `cargo run` with extra words and a program that changes words to uppercase or lowercase.
What it assumes
Assumes Rust is installed and introduces `Args` while using loops, iterators, and matching to process its values.
What you can do after
Build it from scratch: read arguments with `std::env::args()`, skip the program name, and act on supplied words.
How it connects
Connects command-line arguments to iterators, string matching, standard input, and environment variables.

Also explained in

Compare how 14 books explain command-line argument →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.