Code Logo

Transform with Option::map()

Published at25 Jul 2026
Rust Functions Easy 0 views
Like0

Write a Rust function that takes an Option and returns a new Option with the value doubled using Option::map(). If the input is Some(value), return Some(value * 2). If the input is None, return None without applying the closure.

Option::map() is a combinator that transforms the inner value of an Option using a closure. It applies the closure only if the Option is Some, wrapping the result back into Option automatically. If the Option is None, it returns None without calling the closure. This makes map() a safe and concise alternative to match statements.

The map() method is a cornerstone of Rust's functional approach to optional values. It composes well with other combinators like and_then(), unwrap_or(), and filter(). Using map() eliminates boilerplate match arms and makes code more readable by focusing on the transformation logic rather than the None-case handling.

Time complexity is O(1) as map() is a simple enum variant check and optional closure call. Space complexity is O(1). The method inlines to efficient conditional code without runtime overhead.

Edge cases include Some with zero (0 * 2 = 0, still Some), None input (returns None), negative values (correctly doubled), and ensuring the closure only runs on Some values, never on None.

Example Input & Output

Example 1
Input
Some(-3)
Output
Some(-6)
Explanation

Negative doubled

Example 2
Input
None
Output
None
Explanation

None propagates through map

Example 3
Input
Some(5)
Output
Some(10)
Explanation

Double the value inside Some

Example 4
Input
None
Output
None
Explanation

None stays None

Example 5
Input
Some(0)
Output
Some(0)
Explanation

Zero doubled is still zero

Algorithm Flow

Recommendation Algorithm Flow for Transform with Option::map()
Recommendation Algorithm Flow for Transform with Option::map()

Solution Approach

fn solution(val: Option<i32>) -> Option<i32> {
    val.map(|x| x * 2)
}

Best Answers

rust - Approach 1
fn solution(val: Option<i32>) -> Option<i32> {
    val.map(|x| x * 2)
}