std-method
Result::and_then
Chain fallible operations with a common error type. A prior Err bypasses the closure; an Ok is passed into it. If two error types differ, convert one intentionally. Expected stdout (not executed): Ok(12) Common mistake: Returning a bare U instead of Result<U,E> from the closure.
Formal Syntax & Structure
rust syntaxrust
fn and_then<U, F: FnOnce(T) -> Result<U,E>>(self, op: F) -> Result<U,E>Working Example
Example Snippetrust
fn main() { let amount = "12".parse::<u32>().map_err(|_| "invalid number"); let checked = amount.and_then(|n| if n <= 20 { Ok(n) } else { Err("too large") }); println!("{checked:?}");}