OpenViSTAI · Agents · Blockchain · Crypto
Menu

OPENVIST LEARN · FREE LESSONS

Result, errors and the question-mark operator

Propagate a failure with ? and report it at the boundary.

Lesson 17 of 30 · About 20 minutes · Beginner · English

By the end of this lesson

Propagate a failure with ? and report it at the boundary.

Before you start

  • Rust 1.90.0 or later, a terminal and a plain-text editor. Examples were tested with Rust 1.90.0, Edition 2024 on Linux.
  • Complete lesson 16, or be comfortable explaining and running its examples.

Three words to know

Result
Either a successful Ok value or an Err value.
Propagation
Return a failure to the caller instead of handling it here.
Error boundary
The point where failures become user-facing output.

1. Understand the idea

Result<T, E> represents an operation that may fail. ? extracts Ok or returns an error from the surrounding function. It does not ignore the failure and does not automatically print it. A small helper can return detailed errors while main chooses the public message. Keep secrets and raw input out of error text when they are not needed.

2. Save, run and observe

Save this complete program as lesson.rs in a fresh practice folder. It replaces that lesson file only; keep earlier examples separately. Compile it with rustc, then run the executable. Rust source goes in the editor; rustc and cargo commands go in the terminal.

Validate and propagateRUST · save as lesson.rs
fn pages(raw: &str) -> Result<u16, &'static str> {
    let value: u16 = raw.parse().map_err(|_| "not a number")?;
    if value == 0 { return Err("must be positive"); }
    Ok(value)
}
fn main() {
    match pages("0") {
        Ok(value) => println!("pages={value}"),
        Err(message) => println!("invalid: {message}"),
    }
}
What you should see · example output
invalid: must be positive
Compile and run on macOS/LinuxTERMINAL · Bash or Windows PowerShell
rustc --edition=2024 lesson.rs -o lesson
./lesson

3. Explain the result

parse may fail before the positive-value check. map_err translates its error into our simple error type. ? returns that error to the caller. For this lesson we print the demonstration to stdout; the final CLI places invalid-input messages on stderr and sets exit status 2.

YOUR TURN

A small check before you continue

Will pages("12pages") return 12?

Show a suggested answer

No. Parsing the whole string fails and returns Err("not a number").

Sources and scope

Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.