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>.

8 Likes

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.

21 Likes

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:

option.and_then(f1).and_then(f2).and_then(f3);
5 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.