Give your tool a useful interface.
Read process input without hard-coding configuration.
01 Understand the contract
std::env::args reads UTF-8 command-line arguments, while args_os handles platform strings that may not be valid UTF-8. The first argument normally identifies the executable. Environment variables are optional process configuration, not a secure place to print secrets. Return clear errors and a nonzero exit code for failed operations. Manual argument parsing is suitable for a tiny exercise; the cookbook’s Clap project adds generated help, validation, and predictable options for a larger command-line interface.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn parse_limit(args: &[&str]) -> Result<usize, String> {
match args {
[] => Ok(10),
[value] => value
.parse()
.map_err(|_| "expected a whole-number limit".into()),
_ => Err("expected at most one argument".into()),
}
}
fn main() {
println!("default={}", parse_limit(&[]).unwrap());
println!("custom={}", parse_limit(&["25"]).unwrap());
assert!(parse_limit(&["x"]).is_err());
}default=10 custom=25
- 1
Parsing is isolated from process-global input so it can be tested.
- 2
The empty argument list has an explicit default.
- 3
Malformed values remain errors.
cargo run -p lesson_cli_environment03 Mind the boundary
04 Your next build
Reject a zero limit and test missing, invalid, zero, and positive inputs.
Reveal one possible solution +
fn limit(s: Option<&str>) -> Result<usize, String> {
let n = s
.unwrap_or("10")
.parse::<usize>()
.map_err(|_| "invalid".to_owned())?;
if n == 0 {
Err("positive limit required".into())
} else {
Ok(n)
}
}
fn main() {
assert_eq!(limit(None), Ok(10));
assert!(limit(Some("x")).is_err());
assert!(limit(Some("0")).is_err());
assert_eq!(limit(Some("2")), Ok(2));
}05 Check your reasoning
Why isolate parsing from std::env::args?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.