Code Logo

Chain Options with and_then()

Published at25 Jul 2026
Rust Functions Medium 0 views
Like0

Write a Rust function that takes a string, parses it as an integer, then doubles the result, using Option::and_then() to chain the parse and double operations. and_then() is a combinator that applies a function returning Option only if the current Option is Some, otherwise propagates None.

Option::and_then() is the monadic bind operation for Option. It allows chaining computations that may fail. If the Option is Some(value), and_then applies the closure which returns a new Option. If the Option is None, and_then returns None without calling the closure. This eliminates nested match statements and creates a clean pipeline.

The and_then() combinator is fundamental to Rust's error handling philosophy. Unlike exceptions, Rust makes failure modes explicit in the type system and provides combinators like and_then(), map(), and unwrap_or() to compose operations. This approach ensures all failure paths are handled at compile time.

Time complexity is O(1) as and_then is a simple enum match. The string parsing (str::parse) is O(n) where n is the string length. Space complexity is O(1). The combinator itself adds no runtime overhead beyond the operations it chains.

Edge cases include empty strings (parse fails, and_then short-circuits), invalid strings with letters (parse returns None), zero (parses correctly, doubling gives zero), negative numbers, and very large numbers that may overflow the i32 type.

Example Input & Output

Example 1
Input
"42"
Output
Some(42)
Explanation

Parse string to int, double it

Example 2
Input
"abc"
Output
None
Explanation

Invalid integer, parse fails

Example 3
Input
""
Output
None
Explanation

Empty string fails to parse

Example 4
Input
"-5"
Output
Some(-10)
Explanation

Negative parses and doubles

Example 5
Input
"0"
Output
Some(0)
Explanation

Zero parses and doubles to 0

Algorithm Flow

Recommendation Algorithm Flow for Chain Options with and_then()
Recommendation Algorithm Flow for Chain Options with and_then()

Solution Approach

fn solution(s: &str) -> Option<i32> {
    s.parse::<i32>().ok().and_then(|x| Some(x * 2))
}

Best Answers

rust - Approach 1
fn solution(s: &str) -> Option<i32> {
    s.parse::<i32>().ok()
}