Cheatsheet — Unwrap & safety
Extract values from Option and Result safely with unwrap, safeUnwrap, and unwrapErr.
Extraction operators let you get the inner value out of an Option or Result. Use them at boundaries (UI, I/O, tests) rather than in the middle of pipelines.
Extraction operators
| Operator | Description | Usage |
|---|---|---|
unwrap | Get inner value; throws if empty/err (Option & Result) | .unwrap() → value | throws |
safeUnwrap | Get inner value or null (no throw) (Option & Result) | .safeUnwrap() → value | null |
unwrapErr | Get error value; throws if Ok (Result only) | .unwrapErr() → error | throws |
unwrapOr | Get inner value or fallback (Option & Result) | .unwrapOr(fallback) → value |
unwrapOrElse | Get inner value or compute fallback (Option & Result) | .unwrapOrElse(fn) → value |
Guidance
- Prefer staying in the pipeline (
map/flatMap/match*) and only extract at boundaries (UI, I/O, tests). - If you must extract, prefer
safeUnwrap()orunwrapOr()for non-exceptional flows. - Use
unwrap()only when you're certain the value exists (e.g., after anisOk()check).