called Option::unwrap() on a None value
called Option::unwrap() on a None value in Rust means you called .unwrap() on a Rust Option enum that evaluated to None. unwrap() assumes the value is guaranteed to exist and triggers a panic when it does not.
How do I fix called Option::unwrap() on a None value?
To fix called Option::unwrap() on a None value in Rust, locate the line causing the error and check the values right before it runs. Most occurrences happen because of calling .unwrap() on a hashmap lookup. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.
What does called Option::unwrap() on a None value mean?
Rust has no null values; it models optional presence through the Option<T> enum (Some(T) or None). Calling .unwrap() asserts that the value is always Some(T). When the value is None, the runtime immediately panics with this error message.
Why does called Option::unwrap() on a None value happen?
1. Calling .unwrap() on a HashMap lookup
HashMap::get returns Option<&V>. If the key does not exist, it returns None.
Breaks
let val = map.get("missing_key").unwrap(); // panics!Works
let val = map.get("missing_key").copied().unwrap_or(0);2. Calling .unwrap() on first() of an empty slice
slice.first() returns None if the slice has zero elements.
Breaks
let first = items.first().unwrap();Works
if let Some(first) = items.first() {
// process first element
}How to find it in your own code
Replace .unwrap() with safe pattern matching, if let Some(...), or fallback defaults using .unwrap_or(default) or .unwrap_or_else(|| ...). In functions returning Result or Option, propagate errors using the ? operator.
Try it: fix this bug
easypanicked at 'called `Option::unwrap()` on a `None` value' on empty slice
fn get_first_slice_element(nums: Vec<i32>) -> i32 {
// Calling .first().unwrap() panics when nums is empty
*nums.first().unwrap()
}
fn main() {
println!("{}", get_first_slice_element(vec![]));
}More challenges with this error
Each of these challenges runs into this error or pattern. Find the bug and fix it in your browser — no install, no account needed.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.