snippetrustModeratepending
Rust Option and Result combinators
Viewed 0 times
optionresultmapand_thenunwrap_orcombinatorflatmap
Problem
Need to chain operations on Option and Result types without nested match statements.
Solution
Combinator methods for clean Option/Result handling:
// Option combinators
let name: Option<String> = Some("Alice".to_string());
// map: transform inner value
let upper = name.map(|n| n.to_uppercase()); // Some("ALICE")
// and_then (flatMap): chain operations that return Option
fn find_user(name: &str) -> Option<User> { ... }
fn get_email(user: &User) -> Option<String> { ... }
let email = find_user("alice")
.and_then(|user| get_email(&user)); // Option<String>
// unwrap_or: provide default
let name = maybe_name.unwrap_or("Anonymous".to_string());
let name = maybe_name.unwrap_or_default(); // Uses Default trait
// unwrap_or_else: lazy default
let name = maybe_name.unwrap_or_else(|| generate_name());
// filter: conditional Some
let positive = Some(42).filter(|&x| x > 0); // Some(42)
let positive = Some(-1).filter(|&x| x > 0); // None
// Result combinators
let result: Result<i32, String> = Ok(42);
// map / map_err: transform Ok or Err
let doubled = result.map(|v| v * 2); // Ok(84)
let with_context = result.map_err(|e| format!("failed: {e}"));
// ok() / err(): Convert to Option
let maybe: Option<i32> = result.ok(); // Some(42)
// and_then: chain fallible operations
fn parse(s: &str) -> Result<i32, ParseIntError> { s.parse() }
fn double_if_positive(n: i32) -> Result<i32, String> {
if n > 0 { Ok(n * 2) } else { Err("not positive".into()) }
}
"42".parse::<i32>()
.map_err(|e| e.to_string())
.and_then(double_if_positive) // Ok(84)Why
Combinators replace nested match/if-let statements with a fluent, functional pipeline that's easier to read and compose.
Context
Rust code handling optional and fallible values
Revisions (0)
No revisions yet.