liveBook · Manning

Unwrap

As explained in Idiomatic Rust

unwrap is a method that extracts the value from a successful result-like type and panics when extraction fails.

unwrap extracts the value from an Option or Result when it is present or successful; extraction failure panics. It can be convenient, but using it as a shortcut may hide failure paths and signal incomplete error handling. section 10.10 section 10.3

Choose an alternative that matches how the program should handle failure:

  • Use expect to add a custom message; reserve it for cases where failure should stop the program, such as debugging or an expected exit. section 10.3
  • Use map to transform a present or successful value, and and_then to chain operations that return Option or Result. section 10.3
  • Use unwrap_or to supply a default, or ? to propagate a Result error up the call stack. section 10.3

unwrap is not always inappropriate: it may be reasonable when success is sufficiently certain. Otherwise, consider what should happen when a value is absent or an operation fails before choosing how to handle it. section 10.3

let successes: Vec<_> =
    successes.into_iter().map(Result::unwrap).collect();
let failures: Vec<_> =
    failures.into_iter().map(Result::unwrap_err).collect();
println!("successses={:?}", successes);
println!("failures={:?}", failures);

This iterator example unwraps successful parse results after successes and failures have already been partitioned. section 3.2.5

How Idiomatic Rust covers it

How deep it goes
Explains failure risks and alternatives, but does not detail the method’s implementation.
Examples
Demonstrates unwrapping parsed results after partitioning successful and failed integer parses.
What it assumes
Assumes familiarity with Option and Result values rather than teaching them from zero.
What you can do after
Evaluate unwrap use by identifying failure paths and choosing a suitable alternative.
How it connects
Connects unwrap with Option, Result, expect, map, and_then, unwrap_or, 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 Idiomatic Rust. The section links point to the parts of the book it draws on.