Transform Error with map_err()
Write a Rust function that takes a Result
Rust uses Result
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
Negative doubled
Short error string
Err string prefixed with "ERROR: "
Ok(0) doubled to Ok(0)
Ok(10) doubled to Ok(20)
Algorithm Flow
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.
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
fn solution(val: Result<i32, String>) -> Result<i32, String> {
val.map(|x| x * 2).map_err(|e| format!("ERROR: {}", e))
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
