Command-Line Args

Command-line arguments are the values a user types after a program's name, read in Rust through std::env::args() as an iterator of String s — with the program's own name always sitting at index 0.

Learn Command-Line Args in our free Rust course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick reference.

Part of the free Rust course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

In this lesson you'll collect arguments into a , skip the program name, parse arguments into numbers with parse , read environment variables with env::var , and build a small argument-driven program.

What You'll Learn in This Lesson

1️⃣ Reading args() and the Program Name

std::env::args() gives an iterator of String s; .collect() turns it into a you can index and count. Remember that args[0] is always the program's own name, so your real arguments begin at args[1] . A common idiom is .skip(1) to step over the program name.

We simulate the arguments here for reproducibility; in a real program the first line would be and everything else stays the same.

2️⃣ Parsing Arguments Into Numbers

Arguments are always text, so to compute with them you parse() the String into a number, annotating the target type. parse returns a Result because the text might not be a valid number — handle it with match for a clear error, or unwrap_or for a default.

3️⃣ Environment Variables with env::var

Beyond positional arguments, std::env::var(name) reads a named environment variable from the shell, returning a Result : Ok(value) if set, Err if not. Pair it with unwrap_or_else to supply a sensible default for missing variables.

We call set_var here only to make the example self-contained; in real use you'd set APP_MODE in your shell before running. The unset LOG_LEVEL falls back to its default "info" .

Your turn. Fill in the blanks marked ____ , then run it.

Build an argument-driven calculator that reads an operator and two numbers, then prints the result. Run it with cargo run and check the output.

📋 Quick Reference — std::env

Practice quiz

What type does std::env::args() yield for each item?

  • i32
  • &str
  • String
  • char

Answer: String. args() is an iterator of String, usually collected into a Vec<String>.

Where do a program's real (user-typed) arguments begin?

  • Index 1
  • Index 0
  • Index 2
  • The last index

Answer: Index 1. Index 0 is the program name, so the real arguments start at index 1.