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 Vec<String> , 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 Vec<String> 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 let args: Vec<String> = std::env::args().collect(); 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.
Mini-Challenge: A Tiny CLI Calculator
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.
Common Errors (and the fix)
- ❌ index out of bounds: the len is 1 but the index is 1 — you read args[1] with no real arguments given. ✅ Fix: check args.len() first.
- ❌ type annotations needed on parse() — the compiler can't tell which number type. ✅ Fix: annotate, e.g. let n: i64 = s.parse()... .
- ❌ Program crashes on bad input — a bare .unwrap() on a failed parse. ✅ Fix: use unwrap_or or match .
- ❌ Forgetting that args[0] is the program — off-by-one indexing. ✅ Fix: start real args at index 1, or .skip(1) .
Pro Tips
- 💡 Pass real args locally with cargo run -- foo bar — everything after -- goes to your program.
- 💡 Validate before indexing: check args.len() and print a usage message if arguments are missing.
- 💡 Reach for clap once you need flags, subcommands, and help text — but the standard library is plenty for simple tools.
📋 Quick Reference — std::env
Call
Gives
env::args()
iterator of arg Strings
.collect::<Vec<String>>()
all args in a Vec
args[0]
the program name
s.parse::<i64>()
String to number (Result)
env::var("NAME")
an env variable (Result)
Frequently Asked Questions
🎉 Lesson Complete!
- ✅ env::args() yields the arguments; .collect() makes a Vec<String>
- ✅ args[0] is the program name — real args start at index 1
- ✅ parse() turns an argument String into a number (a Result )
- ✅ env::var(name) reads an environment variable, with a fallback for missing ones
- ✅ Pass real arguments locally with cargo run -- a b c
- ✅ Next lesson: Checkpoint — Traits & Generics put it all together
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.
Continue this course
- Previous: File I/O
- Next: Checkpoint: Traits & Generics