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就可以避免.

相关推荐
techdashen19 小时前
Rust OnceCell 深度解析:延迟初始化的优雅解决方案
开发语言·oracle·rust
superman超哥20 小时前
Serde 的零成本抽象设计:深入理解 Rust 序列化框架的哲学
开发语言·rust·开发工具·编程语言·rust序列化
星辰徐哥20 小时前
Rust函数与流程控制——构建逻辑清晰的系统级程序
开发语言·后端·rust
superman超哥1 天前
序列化格式的灵活切换:Serde 生态的统一抽象力量
开发语言·rust·编程语言·rust serde·序列化格式·rust序列化格式
superman超哥1 天前
派生宏(Derive Macro)的工作原理:编译时元编程的艺术
开发语言·rust·开发工具·编程语言·rust派生宏·derive macro·rust元编程
superman超哥1 天前
处理复杂数据结构:Serde 在实战中的深度应用
开发语言·rust·开发工具·编程语言·rust serde·rust数据结构
superman超哥1 天前
错误处理与验证:Serde 中的类型安全与数据完整性
开发语言·rust·编程语言·rust编程·rust错误处理与验证·rust serde
禁默1 天前
【鸿蒙PC命令行适配】rust应用交叉编译环境搭建和bat命令的移植实战指南
华为·rust·harmonyos
superman超哥1 天前
自定义序列化逻辑:掌控数据编码的每一个细节
开发语言·rust·编程语言·rust自定义序列化·rust数据编码
superman超哥1 天前
Serialize 与 Deserialize Trait:Rust 类型系统与序列化的完美融合
开发语言·rust·开发工具·编程语言·rust序列化·rust类型·serialize