CLI arguments

Contents
env::args
Skip argv0
Parse numbers
Print usage

env::args

Every Rust program can read the words typed after its name. The iterator std::env::args yields one String per word, so collect it into a vector and loop over it:

use std::env; fn main() { let args: Vec<String> = env::args().collect(); for arg in &args { println!("{}", arg); } }

Run the program with extra words and each one is printed on its own line. This pattern is the start of every command line tool in this course.

Skip argv0

The first item is always the program path itself, known as argv0. Real arguments start at index 1, so skip the first item:

use std::env; fn main() { let args: Vec<String> = env::args().skip(1).collect(); for arg in &args { println!("{}", arg); } }

Parse numbers

Arguments arrive as text, so convert them when you need numbers. The parse method returns a Result, and unwrap takes the value when the text is valid:

use std::env; fn main() { let arg = env::args().nth(1).unwrap(); let n: u32 = arg.parse().unwrap(); println!("doubled: {}", n * 2); }

The nth(1) call grabs the first real argument. If the user types a number, the program prints twice its value.

Print usage

Always tell the user what you expected when the arguments are wrong. Check the length, print to stderr, and exit with a nonzero status:

use std::env; use std::process; fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 2 { eprintln!("usage: wordfreq <file>"); process::exit(1); } }

A usage line is a tiny contract with the user. Lesson 47 turns this pattern into a full wordfreq tool.

Next: Environment variables

Article author: Arthur Isaev

Related articles
Rust
Rust course: zero to hero in 50 lessons
What is Rust and where it runs
Install Rust
cargo new
Your first program
Variables
Numbers
Strings
Booleans
Tuples
Arrays
Vectors
Slices
if and else
match
Loops
Ownership
Borrowing
Lifetimes
Functions
Structs
Enums in Rust
Advanced match in Rust
Option combinators in Rust
Result and the question mark in Rust
Advanced strings in Rust
Vec methods in Rust
HashMaps in Rust
Modules in Rust
Crates and workspaces in Rust
Testing in Rust
Error handling
Traits
Generics
Trait bounds
Closures
Iterators
Smart pointers
Threads
Mutex and Arc
Files
CLI arguments
Environment variables
Diagnostics
Time
Parsing strings
TCP networking
Capstone: wordfreq CLI
Capstone: tiny HTTP server
Modern Rust tour
Hero roadmap: the whole course on one page
Install Rust on Windows 11
Install Rust on Ubuntu
Install Rust on Rocky Linux
Install Rust on macOS
Install Rust on FreeBSD
Rust in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: