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




