banner
davirain

davirain

twitter
github
知乎
twitter

What is the difference between `and_then` and `map` in usage?

In Rust, and_then and map are methods used for transforming Option or Result types, but they have different usage patterns.

The map method maps an Option or Result<T, E> to a new Option or Result<U, E>, where the operation in the function closure is applied to the value contained in the Option or Result. If the original value is None or Err, the mapping function will not be executed and instead a new None or Err will be returned.

For example, here is an example of using the map method to double the value in an Option:

let some_number = Some(5);
let doubled = some_number.map(|x| x * 2);
assert_eq!(doubled, Some(10));

The and_then method is similar to map in usage, but its return type is Option or Result<U, E> instead of U. In the closure of and_then, we must return a new Option or Result instead of directly returning a value. This means that and_then can be used to transform one Option or Result into another, while also performing some logical tests.

For example, here is an example of using the and_then method to multiply the value in an Option by 3, returning None if the value is less than 10:

let some_number = Some(5);
let result = some_number.and_then(|x| {
    if x < 10 {
        None
    } else {
        Some(x * 3)
    }
});
assert_eq!(result, None);

let some_number = Some(11);
let result = some_number.and_then(|x| {
    if x < 10 {
        None
    } else {
        Some(x * 3)
    }
});
assert_eq!(result, Some(33));

Therefore, in usage, map is used for simple value transformations, while and_then is used for more complex operations and logical tests.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.