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

相关推荐
特立独行的猫a7 小时前
Tauri 应用移植到 OpenHarmony/鸿蒙PC完整指南
华为·rust·harmonyos·tauri·移植·鸿蒙pc
搬砖魁首11 小时前
基础能力系列 - 多线程2 - 条件变量
c++·rust·条件变量·原子类型·线程同步互斥
Yuyubow15 小时前
gpui step by step 5. FocusHandle 焦点处理与键盘点击事件
rust
techdashen16 小时前
在 Fly.io 上使用 Rust 构建远程开发环境:从 Tokio 到 eBPF
开发语言·后端·rust
星栈20 小时前
用 Rust + Makepad 做一个 JSON 查看器:从零到能用的全过程
前端·rust
日取其半万世不竭20 小时前
Rust《腐蚀》 服务器低成本怎么开?配置、端口和存档避坑
服务器·开发语言·rust
techdashen21 小时前
Cargo 1.93 开发周期动态全解析
rust
Vallelonga21 小时前
Rust 中的枚举
开发语言·rust
薛定谔的猫-菜鸟程序员1 天前
从Electron到Tauri,Rust+Vue(Tauri) 实现超高性能桌面日志应用开发,以及开发避坑指南
vue.js·rust·electron