Sub topic 2
Transforming Options and Results in Rust
Assume basic Rust syntax, enums, ownership, closures, and iterators. Option<T> represents a value that may be absent. Result<T, E> represents success or failure. Combinators transform these values without manually matching every variant.
Transforming `Option`
map applies a function only when an Option is Some. It preserves None.
let name = Some(" Ferris ");
let length = name.map(str::trim).map(str::len).unwrap_or(0);
assert_eq!(length, 6);and_then is useful when the transformation already returns an Option. It avoids creating Option<Option<T>>.
fn parse_even(text: &str) -> Option<i32> {
text.parse().ok().filter(|n| n % 2 == 0)
}
let value = Some("24").and_then(parse_even);
assert_eq!(value, Some(24));filter keeps a Some value only when its predicate returns true. unwrap_or supplies a value when the option is None. Use unwrap_or_else when calculating the fallback is expensive or has side effects.
> callout note > These methods return new values. They do not modify the original Option unless you assign the result back to it.
Transforming `Result`
For Result<T, E>, map transforms only the success value. map_err transforms only the error. and_then chains an operation that can fail.
fn port(text: &str) -> Result<u16, String> {
text.parse::<u16>().map_err(|e| format!("invalid port: {e}"))
}
let result = port("8080").and_then(|p| {
if p > 1024 {
Ok(p)
} else {
Err(String::from("port is reserved"))
}
});
assert_eq!(result.map(|p| p + 1), Ok(8081));Converting `Option` and `Result`
Use ok_or or ok_or_else when missing data should become a specific error. Use ok when an error can be discarded and only success matters.
fn required_port(value: Option<&str>) -> Result<u16, String> {
let text = value.ok_or_else(|| String::from("port is missing"))?;
text.parse::<u16>().map_err(|e| e.to_string())
}Propagating with `?`
The ? operator returns early when its operand is Err or None. Therefore, the enclosing function must return a compatible Result or Option.
fn read_port(value: Option<&str>) -> Result<u16, String> {
let text = value.ok_or("missing port")?;
text.parse::<u16>().map_err(|e| e.to_string())
}Exercise
Which method should you use to turn an Option<&str> into a Result<&str, String> with a lazily created error?
Show answer
Use ok_or_else.