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

相关推荐
大卫小东(Sheldon)5 分钟前
集成AI 的 Redis 客户端 Rudist发布新版了
ai·rust·rudist
无心水1 小时前
【时间利器】5、多语言时间处理实战:Go/C#/Rust/Ruby统一规范
golang·rust·c#·时间·分布式架构·openclaw·openclaw变现
Source.Liu1 小时前
【Rust】Rust 项目结构详解
rust
thulium_1 小时前
Rust 编译错误:link.exe 未找到
开发语言·后端·rust
Source.Liu2 小时前
【rust】Rust 默认引用 std::prelude
rust
Source.Liu2 小时前
【rust】VSCode Rust 开发扩展推荐
rust
大卫小东(Sheldon)18 小时前
大模型智能体 (agent)简易流程介绍
ai·rust
小杍随笔20 小时前
【Rust 语言编程知识与应用:同步机制详解】
开发语言·算法·rust
Rust研习社1 天前
Rust 错误处理:thiserror 和 anyhow 的使用
rust
RE-19011 天前
Polars:告别 Pandas 性能瓶颈,用 Rust 驱动的 DataFrame 库处理亿级数据
开发语言·rust·pandas·polars·ai生成