Option Combinators
Option provides combinators to transform and chain optional values without nested match.
Busca en todas las páginas de la documentación
Option provides combinators to transform and chain optional values without nested match.
fn port_from_env() -> Option<u16> {
std::env::var("PORT").ok()
.and_then(|s| s.parse().ok())
}When to reach for this: Pipelines where absence is normal, not an error requiring Result.
struct User { name: String, nickname: Option<String> }
fn display_name(u: &User) -> String {
u.nickname.as_ref()
.map(|n| format!("{} ({})", u.name, n))
.unwrap_or_else(|| u.name.clone())
}
fn main() {
let u = User { name: "Ada".into(), nickname: Some("ad".into()) };
println!("{}", display_name(&u));
}What this demonstrates:
map / as_ref avoid movingunwrap_or_else lazy defaultKey methods: map, and_then, filter, or, or_else, unwrap_or, unwrap_or_default, ok_or, transpose, zip.
None. Fix: unwrap_or or ? with ok_or.map on owned Option - Consumes. Fix: as_ref/as_mut.flatten (1.29+).and vs and_then - and replaces with constant Option. Fix: Read docs per method.ok_or when absence is error.| Alternative | Use When | Don't Use When |
|---|---|---|
match | Complex branches | Simple map chain |
if let | One pattern | Long combinator chain |
Result | Need error reason | Legitimate absence |
MaybeUninit | uninitialized (unsafe) | Normal optional value |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026