Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Rust Command Line Arguments

Many programs are started with extra words after their name. When you type cargo new hello, the word hello tells cargo what to call the project. These extra words are called command line arguments, and your own Rust programs can read them too. They are a quick way to give a program its input without asking questions.

Reading the arguments

std::env::args() gives you an iterator over the arguments. The first one is always the path of the program itself (here target/debug/main), and the words you typed follow. Collecting them into a vector is the usual first step, and skip(1) steps over the program's own name:

use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    println!("It got {} extra argument(s)", args.len() - 1);
    for (i, arg) in args.iter().enumerate().skip(1) {
        println!("Argument {}: {}", i, arg);
    }
}
Output
It got 0 extra argument(s)

The Run button starts the program without any extra words. To pass some, type the command in the terminal yourself. With cargo, the arguments for your program come after two dashes, so that cargo does not think they are meant for itself:

cargo run -- apple banana

Then the program prints It got 2 extra argument(s), followed by both words. If you build with rustc main.rs, you can also run ./main apple banana directly.

A small calculator

Arguments are always text, so numbers must be parsed, just like input from the keyboard. A friendly program also explains how to use it when the arguments are missing, instead of stopping with an index error:

use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() != 3 {
        println!("Usage: cargo run -- <number> <number>");
        println!("Example: cargo run -- 6 7");
        return;
    }
    let a: f64 = match args[1].parse() {
        Ok(n) => n,
        Err(_) => { println!("{} is not a number", args[1]); return; }
    };
    let b: f64 = match args[2].parse() {
        Ok(n) => n,
        Err(_) => { println!("{} is not a number", args[2]); return; }
    };
    println!("{} x {} = {}", a, b, a * b);
}
Output
Usage: cargo run -- <number> <number>
Example: cargo run -- 6 7

Try cargo run -- 6 7 in the terminal and you get 6 x 7 = 42. Try cargo run -- six 7 and you get a polite message instead of a panic.

Arguments or input?

Arguments suit programs that do one job and finish, like a converter or a file tool, and they make it easy to repeat a command with the up arrow. Keyboard input with read_line suits programs that have a conversation with the user, like a quiz or a game. Many real tools offer both.

Practice exercises

  1. Write a program that greets every name given as an argument, or says "Hello, stranger!" when there are none.
  2. Make a converter that takes a temperature in Celsius as an argument and prints it in Fahrenheit.
  3. Add up all the numbers given as arguments, skipping any that are not numbers.