[Avg. reading time: 8 minutes]

Command Line Arguments

Command Line Arguments allow you to pass inputs to a Rust program when the program starts.

They are commonly used for:

  • File paths
  • Configuration values
  • Flags and modes
  • Runtime parameters

Many tools you use daily rely on command line arguments.

Example:

cargo --version
cargo : executable file

--version : argument passed to the program

Accessing Command Line Arguments

Rust provides the function:

std::env::args()

Characteristics:

  • Returns an iterator of String values
  • Each element represents one argument
  • The first argument is always the executable path

Example: Printing All Arguments

use std::env;

fn main() {
    for (index, argument) in env::args().enumerate() {
        println!("{index} -> {argument}");
    }
}
cargo run hello world 123 3.14

Getting a Specific Argument

Using nth()

You can access a specific argument using nth().

use std::env;

fn main() {
    let second = env::args().nth(1);
    println!("{:?}", second);
}

Important details:

  • nth(1) returns Option
  • The argument might not exist
  • Rust forces you to handle missing values safely

Using skip() and next()

use std::env;

fn main() {
    let name = env::args().skip(1).next();
    println!("{:?}", name);
}
skip(1) ignores the executable path

next() returns the first remaining argument

Using Option

There is no guarantee users enter necessary arguments.

use std::env;

fn main() {
    let name = env::args().skip(1).next();

    match name {
        Some(n) => println!("Hello {n}"),
        None => {
            println!("Missing argument");
            std::process::exit(1);
        }
    }
}

This avoids panic!

CLI programs should:

  • Fail gracefully
  • Display useful messages
  • Exit with a non-zero status code

Parsing Args

Command line inputs are always text and must be converted to Numbers or respective datatypes.

use std::env;

fn main() {
    let age: u32 = env::args()
        .nth(2)
        .expect("Missing age")
        .parse()
        .expect("Age must be a number");

    println!("Age: {}", age);
}
String -> parse() -> numeric type

Using Message Pattern

Good CLI program prints a usage message when arguments are missing

use std::env;

fn print_help(program: &str) {
    println!("Usage: {} <name>", program);
    println!();
    println!("Arguments:");
    println!("  <name>        Name of the person to greet");
    println!();
    println!("Options:");
    println!("  -h, --help    Show this help message");
}

fn main() {
    let mut args = env::args();

    let program = args.next().unwrap();

    let first = args.next();

    match first.as_deref() {
        Some("-h") | Some("--help") => {
            print_help(&program);
        }

        Some(name) => {
            println!("Hello {name}");
        }

        None => {
            eprintln!("Missing argument\n");
            print_help(&program);
            std::process::exit(1);
        }
    }
}
cargo run -h
cargo run Rachel

Advance CLI Parser utilities

#cli #commandlineargsVer 2.0.19

Last change: 2026-03-04