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

相关推荐
小杍随笔7 分钟前
【Rust 语言编程知识与应用:元编程详解】
开发语言·后端·rust
希夷小道12 分钟前
gitru:一个由 Rust 打造的零依赖 Git 提交信息校验工具
git·rust
Ivanqhz34 分钟前
linearize:控制流图(CFG)转换为线性指令序列
开发语言·c++·后端·算法·rust
集智飞行44 分钟前
安装rust和cargo
开发语言·后端·rust
beifengtz2 小时前
Rust 实现 KCP 可靠 UDP 通信:kcp-io 库快速上手指南
网络协议·rust·udp·kcp
Source.Liu18 小时前
【Rust】Cargo 命令详解
rust
大卫小东(Sheldon)1 天前
集成AI 的 Redis 客户端 Rudist发布新版了
ai·rust·rudist
无心水1 天前
【时间利器】5、多语言时间处理实战:Go/C#/Rust/Ruby统一规范
golang·rust·c#·时间·分布式架构·openclaw·openclaw变现
Source.Liu1 天前
【Rust】Rust 项目结构详解
rust