liveBook · Manning

Expect

As explained in Refactoring to Rust

The Rust expect operation extracts a contained Option or Result value and panics with a supplied message on absence or error.

Rust’s expect operation extracts the success value from a Result. If the Result contains an error, it panics and adds a message you supply, making the failure more descriptive than unwrap’s default message. section 2.5.6 section 2.6

Adding context to a FizzBuzz failure

Replace a manual error match with `match fizzbuzz(x).expect("Failed to run fizzbuzz")`. For negative input, the program panics with `Failed to run fizzbuzz: GotNegative`, identifying both the operation and the error.

fn print_fizzbuzz(x: i32) {
  match fizzbuzz(x).expect("Failed to run fizzbuzz") {
    FizzBuzzValue::FizzBuzz => {
      println!("FizzBuzz");
    }
    FizzBuzzValue::Fizz => {
      println!("Fizz");
    }
    FizzBuzzValue::Buzz => {
      println!("Buzz");
    }
    FizzBuzzValue::NotDivisible(num) => {
      println!("{}", num);
    }
  }
}

Compare the shorter expect-based implementation with the earlier match that handles the error explicitly. section 2.5.6

How Refactoring to Rust covers it

How deep it goes
Explains extraction, custom panic messages, and observed output, but stops short of broader implementation details.
Examples
Demonstrates expect in FizzBuzz with a negative input and a Cargo run showing the resulting panic.
What it assumes
Assumes familiarity with Result and its success or error cases while introducing expect alongside explicit matching and unwrap.
What you can do after
Apply it to replace explicit Result error matching when panicking with operation-specific context is appropriate.
How it connects
Connects expect with Result, unwrap, panic!, the ? operator, and Debug.

Also explained in

Compare how 2 books explain expect →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.