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

相关推荐
小灰灰搞电子1 小时前
Rust std::vec::Vec<T>动态数组:所有相关 API 全面介绍
开发语言·rust
学习星球1 小时前
CodeWhale 深度剖析:从 DeepSeek-TUI 到 40.9K Star 的 Rust 终端编程 Agent
开发语言·后端·rust
小灰灰搞电子3 小时前
Rust 相关容器(集合)详解
开发语言·容器·rust
小灰灰搞电子21 小时前
Rust+Slint 实现侧滑菜单栏源码分享
开发语言·rust·抽屉式菜单栏
qq_406981031 天前
大白话rust系列01注释
开发语言·rust
zLLM_Lab1 天前
GPU kernel 已返回,显存为什么还不能释放?用 Rust 管理 CPU/GPU 完整生命周期
rust·gpu
对象存储与RustFS1 天前
给 RustFS 拆多租户权限:IAM 用户、组与策略的实战
后端·rust·开源
小灰灰搞电子1 天前
Rust+Slint 实现蜂巢菜单源码分享
开发语言·rust·蜂巢菜单.
mldong1 天前
流程实例如何沿着箭头走到结束:Rust 工作流引擎的执行内核
架构·rust