Result Combinators
Medium
+3 pts
Error Handling
3/4
Result<T, E> is like Option, but carries error information. The same combinator patterns apply.
Quick recap
enum Result<T, E> {
Ok(T), // success with value
Err(E), // failure with error
}
In Python, you'd use exceptions. Rust uses return values — errors are data, not control flow.
.map() — transform success value
let result: Result<i32, String> = Ok(5);
let doubled = result.map(|n| n * 2); // Ok(10)
let result: Result<i32, String> = Err("oops".to_string());
let doubled = result.map(|n| n * 2); // Err("oops") — unchanged
.map_err() — transform the error
let result: Result<i32, &str> = Err("not found");
let better = result.map_err(|e| format!("Error: {}", e));
// Err("Error: not found")
Useful for converting between error types.
.and_then() — chain Result-returning functions
fn parse(s: &str) -> Result<i32, String> {
s.parse().map_err(|_| "parse error".to_string())
}
fn validate(n: i32) -> Result<i32, String> {
if n > 0 { Ok(n) } else { Err("must be positive".to_string()) }
}
let result = parse("42").and_then(validate); // Ok(42)
let result = parse("-5").and_then(validate); // Err("must be positive")
let result = parse("abc").and_then(validate); // Err("parse error")
.unwrap_or() and .unwrap_or_else()
let value = result.unwrap_or(0); // 0 if Err
let value = result.unwrap_or_else(|e| {
eprintln!("Error: {}", e);
0
});
.ok() — convert Result to Option
let result: Result<i32, &str> = Ok(42);
let option: Option<i32> = result.ok(); // Some(42)
let result: Result<i32, &str> = Err("nope");
let option: Option<i32> = result.ok(); // None — error is discarded
Your Task
safe_sqrt(n: f64) -> …
Login to see the full exercise.
Topics