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

相关推荐
CHANG_THE_WORLD2 小时前
Rustup 安装加速:使用国内镜像源解决下载慢问题
rust·rustup
萧曵 丶11 小时前
Rust 仿射类型(Affine Types)
rust·仿射类型
寻月隐君14 小时前
Rust核心利器:枚举(Enum)与模式匹配(Match),告别空指针,写出优雅健壮的代码
后端·rust·github
泊浮目1 天前
生产级Rust代码品鉴(一)RisingWave一条SQL到运行的流程
大数据·后端·rust
得物技术1 天前
从Rust模块化探索到DLB 2.0实践|得物技术
rust
寻月隐君2 天前
不止于后端:Rust 在 Web 开发中的崛起之路 (2024数据解读)
后端·rust·github
萧曵 丶3 天前
Rust 所有权系统:深入浅出指南
开发语言·后端·rust
GetcharZp3 天前
彻底告别数据焦虑!这款开源神器 RustDesk,让你自建一个比向日葵、ToDesk 更安全的远程桌面
后端·rust
solohoho3 天前
Rust:结构体、方法生命周期标注核心要义
rust
Humbunklung4 天前
Rust枚举:让数据类型告别单调乏味
开发语言·后端·rust