What Is the difference between `map` and `and_then`

As I read the docs I just cannot figure out the differences between and_then and map for types like Option or Result. They both seem to be mapping lets say an Option<T> to Option<U>.

The argument to the closure (or Fn) that you provide. map takes a FnOnce(T) -> U whereas and_then takes a FnOnce(T) -> Option<U>. With and_then you can combine several operations which each may individually fail, whereas map applies an infallible transformation.


option.map() transforms Option<T> to Option<U>, while
and_then is a like a short circuiting boolean-AND operation
for option.map(). The long form is:

match option {
  None => None,
  val => match val.map(f1) {
    None => None,
    val => match val.map(f2) {
      None => None,
      val => val.map(f3),

short form is:

1 Like