All lessons

Lesson 10 of 11

Recoverable errors

Follow a parse error through a function and handle it with Result.

main.rs

use std::num::ParseIntError;fn passes(text: &str) -> Result<bool, ParseIntError> {    let score: u32 = text.parse()?;    Ok(score >= 10)}fn main() {    for text in ["12", "oops"] {        match passes(text) {            Ok(pass) => println!("Passes: {pass}"),            Err(_) => println!("Enter a whole number."),        }    }}

Program state

Inputs
"12", "oops"
Step 1 of 8

The program checks two pieces of text against a minimum score of 10.

What’s happening

A Result holds either a success in Ok or a failure in Err. Parsing text as a u32 can fail, so the parser returns a Result with a ParseIntError in its failure case.

After a call that returns Result, ? gives you the value inside Ok. On Err, it returns the error from the current function immediately. The caller can use match to decide what to do about either outcome.

Read more in The Rust Book