Option combinators in Rust

Contents
Map the inside
Chain with and_then
unwrap expect unwrap_or
Early return pattern

Map the inside

Map transforms the value inside Some and leaves None alone. Give map a closure, and it applies the closure only when a value is present.

The result stays an Option, so absence flows through long chains without extra checks.

fn main() { let a = Some(3); let b = a.map(|x| x + 1); println!("done"); }

Here b becomes Some holding 4. If a were None, map would skip the closure and b would stay None.

Chain with and_then

Use and_then when the next step also returns an Option. The closure runs only for Some, and its result becomes the new value, which flattens two layers into one.

Parsing text is a classic case: convert the string, and a failed parse becomes None automatically.

fn to_num(s: String) -> Option<i32> { s.parse().ok() } fn main() { let r = Some(String::from("7")).and_then(to_num); }

The chain starts with text and ends with a number option. Bad input yields None at the parse step with no extra branching.

unwrap expect unwrap_or

Unwrap helpers trade the Option wrapper for a plain value. Prefer unwrap_or with a default so None maps to a safe value instead of stopping the program.

Reserve unwrap and expect for cases that truly cannot fail, since they stop the program on None.

fn main() { let a: Option<i32> = Some(3); let x = a.unwrap_or(0); let y: Option<i32> = None; let z = y.unwrap_or(0); }

Here x becomes 3 and z becomes 0. The same call handles both variants, so callers never branch by hand.

Early return pattern

The let else form returns early when the value is absent. It binds the inner value for the rest of the function and handles None in a short else block.

Use this shape at the top of functions to keep the main path flat and free of deep nesting.

fn double_first(v: Vec<i32>) -> i32 { let Some(x) = v.first().copied() else { return 0; }; x * 2 }

Empty input returns 0 at once, while other input flows into the math below. The bound x is a plain number for the rest of the body.

Next: Result and question mark

Article author: Arthur Isaev

Related articles
Rust
Rust course: zero to hero in 50 lessons
What is Rust and where it runs
Install Rust
cargo new
Your first program
Variables
Numbers
Strings
Booleans
Tuples
Arrays
Vectors
Slices
if and else
match
Loops
Ownership
Borrowing
Lifetimes
Functions
Structs
Enums in Rust
Advanced match in Rust
Option combinators in Rust
Result and the question mark in Rust
Advanced strings in Rust
Vec methods in Rust
HashMaps in Rust
Modules in Rust
Crates and workspaces in Rust
Testing in Rust
Error handling
Traits
Generics
Trait bounds
Closures
Iterators
Smart pointers
Threads
Mutex and Arc
Files
CLI arguments
Environment variables
Diagnostics
Time
Parsing strings
TCP networking
Capstone: wordfreq CLI
Capstone: tiny HTTP server
Modern Rust tour
Hero roadmap: the whole course on one page
Install Rust on Windows 11
Install Rust on Ubuntu
Install Rust on Rocky Linux
Install Rust on macOS
Install Rust on FreeBSD
Rust in Docker
Banner image

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: