Code Logo

Transform Error with map_err()

Published at25 Jul 2026
Rust Functions Medium 3 views
Like0

Write a Rust function that takes a Result and uses map_err() to transform any error by prepending "ERROR: " to the error message. If the Result is Ok, double the value. This demonstrates Rust's Result type for error handling without exceptions.

Rust uses Result for fallible operations. Ok(T) represents success, Err(E) represents failure. The map() method transforms the success value while leaving errors unchanged, and map_err() transforms the error value while leaving successes unchanged. Together they allow processing both paths without explicit match statements.

The map_err() method is especially useful for converting between different error types in a function call chain. Instead of matching on each Result and manually transforming errors, map_err() applies a closure only when the Result is Err. This leads to cleaner, more composable error handling.

Time complexity is O(1) as map_err is a simple enum match. Space complexity is O(1). The method inlines to efficient conditional branches that don't allocate unless the closure allocates.

Edge cases include empty error strings, Ok with various integer values including zero and negatives, and ensuring the success path transformation (doubling) is applied only on Ok values, never on Err.

Example Input & Output

Example 1
Input
Ok(-5)
Output
Ok(-10)
Explanation

Negative doubled

Example 2
Input
Err("x")
Output
Err("ERROR: x")
Explanation

Short error string

Example 3
Input
Err("fail")
Output
Err("ERROR: fail")
Explanation

Err string prefixed with "ERROR: "

Example 4
Input
Ok(0)
Output
Ok(0)
Explanation

Ok(0) doubled to Ok(0)

Example 5
Input
Ok(10)
Output
Ok(20)
Explanation

Ok(10) doubled to Ok(20)

Algorithm Flow

Recommendation Algorithm Flow for Transform Error with map_err()

Solution Approach

Transform the error value in a Result using map_err(). If the result is Err(e), apply the closure to transform the error. If it is Ok(v), remain unchanged. This is useful for converting between error types.

fn solution(r: Result<i32, &str>) -> Result<i32, String> { r.map_err(|e| e.to_string()) }

map_err() only transforms the Err variant, leaving Ok unchanged. The counterpart map() transforms the Ok variant. Both are combinators for ergonomic error handling.

Time O(1), Space O(1).

Best Answers

rust - Approach 1
fn solution(val: Result<i32, String>) -> Result<i32, String> {
    val.map(|x| x * 2).map_err(|e| format!("ERROR: {}", e))
}