Code Logo

Safe Unwrap with unwrap_or()

Published at25 Jul 2026
Rust Functions Medium 0 views
Like0

Write a Rust function that takes an Option and a default value, returning the contained value if present or the default if None, using the unwrap_or() method. This demonstrates Rust's approach to handling nullable values without null pointer exceptions.

Rust does not have null. Instead, it uses the Option enum which can be either Some(T) or None. The unwrap_or() method provides a safe way to extract the value: if the Option is Some, it returns the inner value; if None, it returns the provided default. This eliminates the possibility of null-related crashes at compile time.

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

Example 1
Input
Some(7),3
Output
7
Explanation

Some(7) with default 3 gives 7

Example 2
Input
Some(42),0
Output
42
Explanation

Some(42) unwrap_or gives 42

Example 3
Input
Some(100),-1
Output
100
Explanation

Some(100) with default -1 gives 100

Example 4
Input
None,0
Output
0
Explanation

None unwrap_or gives default 0

Example 5
Input
None,99
Output
99
Explanation

None with default 99 gives 99

Algorithm Flow

Recommendation Algorithm Flow for Safe Unwrap with unwrap_or()
Recommendation Algorithm Flow for Safe Unwrap with unwrap_or()

Solution Approach

fn solution(val: Option<i32>, default: i32) -> i32 {
    val.unwrap_or(default)
}

Best Answers

rust - Approach 1
fn solution(val: Option<i32>, default: i32) -> i32 {
    val.unwrap_or(default)
}