Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ MODEL THE DOMAIN
BUILD NOTE 19 / 53

Failure with useful information.

Return errors that callers can understand and handle.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

Result<T, E> separates successful values from recoverable failures. Parsing input can fail without being a programmer bug, so return an error instead of crashing. The ? operator returns early with an error and unwraps only the success path; the surrounding function must have a compatible return type. Error messages should preserve enough context for the caller to act. Use a domain error enum when callers need structured decisions, and reserve panic for violated invariants or unrecoverable conditions.

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/result/src/main.rs
fn quantity(text: &str) -> Result<u32, String> {
    let n = text
        .parse::<u32>()
        .map_err(|_| "not a whole number".to_owned())?;
    if n == 0 {
        return Err("quantity must be positive".into());
    }
    Ok(n)
}
fn main() {
    println!("{:?}", quantity("3"));
    println!("{:?}", quantity("0"));
}
↳ EXPECTED OUTPUT
Ok(3)
Err("quantity must be positive")
  1. 1

    map_err turns a parse error into a domain message.

  2. 2

    ? propagates the error without nesting another match.

  3. 3

    A parsed zero is still rejected by the business rule.

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

03 Mind the boundary

04 Your next build

A SMALL MISSION

Parse an i32, reject negative values, and test invalid, negative, and valid input.

Reveal one possible solution +
solutions/result/src/main.rs
fn nonnegative(s: &str) -> Result<i32, String> {
    let n = s.parse::<i32>().map_err(|_| "invalid".to_owned())?;
    if n < 0 { Err("negative".into()) } else { Ok(n) }
}
fn main() {
    assert!(nonnegative("x").is_err());
    assert!(nonnegative("-1").is_err());
    assert_eq!(nonnegative("0"), Ok(0));
}

05 Check your reasoning

QUICK SIGNAL CHECK

What does ? do on Err?

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.