Rust:
Reading command line arguments
How to:
Here’s the simplest way to grab arguments:
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
println!("{:?}", args);
}
Run it with cargo run arg1 arg2
. You’ll see:
["path/to/executable", "arg1", "arg2"]
A tidier option with iterators:
use std::env;
fn main() {
for arg in env::args().skip(1) {
println!("{}", arg);
}
}
Now try cargo run cool stuff
:
cool
stuff
Deep Dive
Historically, command line arguments are a throwback to the days when GUIs weren’t widespread. Now, they’re great for scripts, servers, or tools.
Rust’s std::env::args
uses an iterator, which is memory efficient and lazy. It handles Unicode too. There’s also args_os
for raw OS strings.
For complex parsing, crates like clap
or structopt
come in handy. They parse flags, options, and subcommands.