What is the difference between map and and_then for Option

Use map for simple transformations on Option values and and_then when the transformation returns another Option to flatten the result.

Use map to transform the inner value while keeping the Option type, and use and_then when your transformation function returns another Option to avoid nested Option<Option<T>> types.

let x: Option<i32> = Some(5);

// map: Some(5) -> Some(6)
let y = x.map(|n| n + 1);

// and_then: Some(5) -> Some(6) (flattens Option<Option<i32>>)
let z = x.and_then(|n| Some(n + 1));

// and_then with None: Some(5) -> None
let w = x.and_then(|n| if n > 10 { Some(n) } else { None });