unwrap is a Rust method that takes the value out of a successful Result or present Option. If the value is Err or None, unwrap panics instead. Think of it like opening a present: you get the value when one exists, but opening an empty present fails. section 5.2.1 section 5.2.2
Unwrapping an Option
fn try_take_fifth(value: Vec<i32>) -> Option<i32> { if value.len() < 5 { None } else { Some(value[4]) } } let small = vec![1, 2]; let big = vec![1, 2, 3, 4, 5]; println!("{}", try_take_fifth(big).unwrap()); // prints 5 println!("{}", try_take_fifth(small).unwrap()); // panics The second call unwraps None, producing a message such as “called `Option::unwrap()` on a `None` value.” Check the state first or use match when absence is possible.
Use unwrap deliberately:
- Treat it as safe only when the surrounding logic guarantees Some or Ok. section 5.2.1
- Use is_some or is_ok to check state before extraction, or use match to handle every case. section 5.2.2
- Expect a panic and diagnostic location when unwrap receives None or Err; clean up unnecessary unwraps in finished applications. section 24.3.3




