liveBook · Manning

Expect

As explained in Learn Rust in a Month of Lunches

expect is a Rust method that extracts the value from an Option or Result and panics with a supplied message when the value represents absence or failure.

Rust’s expect method extracts a value from an Option or Result. When the value is absent or represents failure, expect panics with the message you provide. section 6.3

Adding a useful failure message

Calling input.get(3).unwrap() on a three-item vector produces the vague message “called Option::unwrap() on a None value.” Replacing it with input.get(3).expect("Input vector needs at least 4 items") reports the actual requirement and the source location. section 6.3

expect is clearer than unwrap because its message documents what the code assumes and helps identify which operation failed. It still panics, so it is useful while writing code or when failure should be impossible, but finished programs should usually use non-panicking handling when customers may encounter the problem. section 6.3

Use expect when:

  • A missing value indicates a violated assumption that should stop the program. section 6.3
  • A custom message can explain the required condition more clearly than unwrap. section 6.3
fn get_fourth(input: &Vec<i32>) -> i32 {
    let fourth = input.get(3).expect("Input vector needs at least 4 items");
    *fourth
}
 
fn main() {
    let my_vec = vec![9, 0, 10];
    let fourth = get_fourth(&my_vec);
}

Compare the expect call with its resulting panic message in b16. section 6.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains expect through Option lookups, panic output, comparison with unwrap, and guidance about later non-panicking handling.
Examples
Demonstrates missing vector elements, custom panic messages, and distinguishing failures among multiple Option values.
What it assumes
Assumes familiarity with vectors and Option values while contrasting expect with unwrap and unwrap_or.
What you can do after
Apply expect to produce clearer panic diagnostics for absent values and violated assumptions.
How it connects
Connects expect with Option, Result, unwrap, panic, and unwrap_or.

Also explained in

Compare how 2 books explain expect →

Related concepts

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