Parse Arguments With env::args
Read command line arguments from std::env::args, validate flags and values, and return process exit codes without any argument-parsing crate.
Code
use std::env;
use std::process::ExitCode;
fn parse_args(args: impl Iterator<Item = String>) -> Result<(String, u16), String> {
let mut path = None;
let mut port = 8080u16;
let mut args = args.skip(1); // 跳过程序名
// Parse arguments manually; no argument-parsing crate is involved
while let Some(arg) = args.next() {
match arg.as_str() {
"--port" => {
let raw = args.next().ok_or("--port needs a value")?;
port = raw.parse().map_err(|_| format!("invalid port: {raw}"))?;
}
other if other.starts_with("--") => {
return Err(format!("unknown flag: {other}"));
}
other => path = Some(other.to_string()),
}
}
match path {
Some(path) => Ok((path, port)),
None => Err(String::from("missing input path")),
}
}
fn main() -> ExitCode {
let args: Vec<String> = env::args().collect();
match parse_args(args.into_iter()) {
Ok((path, port)) => {
println!("path={path} port={port}");
ExitCode::SUCCESS
}
Err(message) => {
eprintln!("error: {message}");
ExitCode::from(2)
}
}
}How it works
One way to read it: the functions parse_args and main, doing all the work.
The file repeats itself only inside while let Some(arg) = args.next(). Fallible operations return Result, and the ? operator short-circuits errors up to the caller. The match covers the value’s shapes one arm at a time — nothing falls to a default by accident.
What to watch for
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Applying it
The primary signature is fn parse_args(args: impl Iterator<Item = String>) -> Result<(String, u16), String>
Running the file prints labeled results such as path= — each operation’s effect is visible in the output.
main is the driver: it invokes parse_args before returning.
Statements that matter
return Err(format!("unknown flag: {other}"));
Ok((path, port)) => {
println!("path={path} port={port}");
ExitCode::SUCCESS
}
Err(message) => {
eprintln!("error: {message}");
ExitCode::from(2)
}
Interactive Tools for This Topic
FAQ
- How should callers handle failures?
- No panics — `Result` values carry the failure, and `?` forwards them to the caller.
- What does Parse Arguments With env::args print when run?
- Execute the whole file; each printed line is prefixed with a label like `path=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.