Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ PACKAGES, FILES & TOOLS
BUILD NOTE 33 / 53

Give your tool a useful interface.

Read process input without hard-coding configuration.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

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.

lessons/cli-environment/src/main.rs
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());
}
↳ EXPECTED OUTPUT
default=10
custom=25
  1. 1

    Parsing is isolated from process-global input so it can be tested.

  2. 2

    The empty argument list has an explicit default.

  3. 3

    Malformed values remain errors.

From the extracted rust-workbench folder
cargo run -p lesson_cli_environment

03 Mind the boundary

04 Your next build

A SMALL MISSION

Reject a zero limit and test missing, invalid, zero, and positive inputs.

Reveal one possible solution +
solutions/cli-environment/src/main.rs
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

QUICK SIGNAL CHECK

Why isolate parsing from std::env::args?

ONE MORE CONTRACT YOU CAN EXPLAIN.

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.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.