Safe Unwrap with unwrap_or()
Write a Rust function that takes an Option
Rust does not have null. Instead, it uses the Option
The unwrap_or() method is preferred over unwrap() in production code because it never panics. While unwrap() will crash the program on None, unwrap_or() gracefully falls back to a default value. This pattern is common in Rust codebases and represents the idiomatic way to handle optional values.
Time complexity is O(1) as unwrap_or is a simple enum match. Space complexity is O(1). The method is a zero-cost abstraction that compiles to efficient conditional branches without runtime overhead.
Edge cases include None with various default values, Some with any inner value, and ensuring the function works with different data types through generics (though this challenge uses i32 specifically).
Example Input & Output
Some(7) with default 3 gives 7
Some(42) unwrap_or gives 42
Some(100) with default -1 gives 100
None unwrap_or gives default 0
None with default 99 gives 99
Algorithm Flow

Solution Approach
Best Answers
fn solution(val: Option<i32>, default: i32) -> i32 {
val.unwrap_or(default)
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
