capypad
0 day streak
rust / intermediate
Snippet

Result and Option Combinators

Option and Result have powerful combinator methods. ok() converts Result to Option. filter() conditionally keeps or discards values. map() transforms the inner value without unwrapping. These chaining methods avoid verbose match statements.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
fn parse_and_add(s: &str) -> Option<i32> {
s.trim()
.parse::<i32>()
.ok()
.filter(|&n| n > 0)
}
 
fn divide(a: i32, b: i32) -> Result<f64, String> {
if b == 0 {
Err(String::from("Division by zero"))
} else {
Ok(a as f64 / b as f64)
}
}
 
fn main() {
let numbers = vec!["42", "hello", "-5", "100"];
for s in numbers {
if let Some(n) = parse_and_add(s) {
println!("Parsed positive: {}", n);
}
}
 
let result = divide(10, 2).map(|v| v * 2.0);
println!("Result: {:?}", result);
}
Breakdown
1
.parse::<i32>()
Returns Result<i32, ParseIntError>, parsed string to integer
2
.ok()
Converts Result<T, E> to Option<T>, discarding the error
3
.filter(|&n| n > 0)
Keeps value only if predicate returns true
4
.map(|v| v * 2.0)
Transforms inner Ok value, leaves Err untouched