Rust中Option、Result的map和and_then的区别

rust 复制代码
Maps a Result<T, E> to Result<U, E> by applying a function to a contained Ok value, leaving an Err value untouched.
This function can be used to compose the results of two functions.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U, E> {
    match self {
        Ok(t) => Ok(op(t)),
        Err(e) => Err(e),
    }
}
Calls op if the result is Ok, otherwise returns the Err value of self.
This function can be used for control flow based on Result values.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
    match self {
        Ok(t) => op(t),
        Err(e) => Err(e),
    }
}

看签名这两个函数返回值都是Result,不同之处在于闭包的返回值,and_then要求我们手动包起来。

map和and_then最大区别就是map在链式调用时可能会出现嵌套的Option或者Result.

如果闭包函数返回值也是一个Option\Result的话,那么整体结果就会出现嵌套,此时使用and_then就可以避免.

相关推荐
superman超哥12 小时前
Rust 枚举与结构体定义:类型系统的代数基石
rust·类型系统·rust枚举与结果体定义·代数基石
superman超哥13 小时前
Rust 基本数据类型:类型安全的底层探索
开发语言·rust·rust基本数据类型·rust底层探索·类型安全
苏近之14 小时前
Rust 中实现定时任务管理
后端·架构·rust
该用户已不存在14 小时前
7个构建高性能后端的 Rust 必备库
后端·rust
superman超哥19 小时前
Rust impl 块的组织方式:模块化设计的艺术
开发语言·后端·rust·模块化设计·rust impl块·impl块
superman超哥20 小时前
Rust 表达式与语句的区别:函数式思维与控制流设计
开发语言·后端·rust·rust表达式·rust语句·函数式思维·控制流设计
superman超哥21 小时前
Rust Trait 定义与实现:类型系统的多态基石
开发语言·rust·类型系统·rust trait·定义与实现·多态基石
superman超哥21 小时前
Rust 方法与关联函数:所有权语义下的行为设计
开发语言·rust·rust底层探索·rust方法与关联函数·所有权语义下的行为设计
superman超哥21 小时前
Rust 复合类型:元组与数组的内存布局与性能优化
开发语言·后端·性能优化·rust·内存布局·rust复合类型·元组与数组
superman超哥1 天前
Rust 函数定义与参数传递:所有权系统下的设计艺术
开发语言·rust·设计艺术·rust函数定义·rust参数传递