liveBook · Manning

Unwrap

As explained in Refactoring to Rust

The Rust unwrap operation extracts a contained Option or Result value and panics on absence or error.

unwrap extracts the success value from a Result and panics when the Result contains an error. It shortens match-based error handling, but the error type must implement Debug so Rust can display the failure. section 2.5.6

Use unwrap when a panic is the intended response to failure:

  • Replace an explicit Err match arm with `fizzbuzz(x).unwrap()`. section 2.5.6
  • Derive Debug for the error type when compilation reports that unwrap's trait bounds are unmet. section 2.5.6
  • Expect a panic message containing the Result error value, such as `GotNegative`, when unwrap receives Err. section 2.5.6
  • Choose expect instead when a custom panic message gives more useful context. section 2.5.6
Listing 2.37 Panicking when print_fizzbuzz sees an error
enum FizzBuzzValue {
  Fizz,
  Buzz,
  FizzBuzz,
  NotDivisible(i32),
}

enum Error {
  GotNegative,
}

fn main() {
  print_fizzbuzz(-1);  #1
}

fn print_fizzbuzz(x: i32) {  #2
  match fizzbuzz(x) {
    Ok(result) => match result {
      FizzBuzzValue::FizzBuzz => {
        println!("FizzBuzz");
      }
      FizzBuzzValue::Fizz => {
        println!("Fizz");
      }
      FizzBuzzValue::Buzz => {
        println!("Buzz");
      }
      FizzBuzzValue::NotDivisible(num) => {
        println!("{}", num);
      }
 #3
    },
    Err(Error::GotNegative) => {
      panic!("Got a negative number for fizzbuzz: {}", x);
    }
  }
}

fn fizzbuzz(x: i32) -> Result<FizzBuzzValue, Error> {
  if x < 0 {
    Err(Error::GotNegative)
  } else if x % 3 == 0 && x % 5 == 0 {
    Ok(FizzBuzzValue::FizzBuzz)
  } else if x % 3 == 0 {
    Ok(FizzBuzzValue::Fizz)
  } else if x % 5 == 0 {
    Ok(FizzBuzzValue::Buzz)
  } else {
    Ok(FizzBuzzValue::NotDivisible(x))
  }
}

Compare the complete FizzBuzz implementation that uses unwrap to panic on negative input. section 2.5.6

How Refactoring to Rust covers it

How deep it goes
Defines extraction, panic behavior, Debug requirements, compiler feedback, runtime output, and the expect alternative.
Examples
Demonstrates unwrap in FizzBuzz, where negative input produces an Err and a printed panic with GotNegative.
What it assumes
Assumes familiarity with Result matching and teaches the Debug derive needed for error reporting.
What you can do after
Apply it via Rust's Result API to extract success values and intentionally panic on errors.
How it connects
Connects unwrap with Result, panic!, expect, Debug, match, and the ? operator.

Also explained in

Compare how 5 books explain unwrap →

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.