Chain Options with and_then()
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
Parse string to int, double it
Invalid integer, parse fails
Empty string fails to parse
Negative parses and doubles
Zero parses and doubles to 0
Algorithm Flow

Solution Approach
Best Answers
fn solution(s: &str) -> Option<i32> {
s.parse::<i32>().ok()
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
