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

相关推荐
迷渡15 小时前
用 Rust 重写的 Bun 有 13365 个 unsafe!
开发语言·后端·rust
咸甜适中16 小时前
rust语言学习笔记Trait(九)PartialEq、 Eq(相等比较)
笔记·学习·rust
恋喵大鲤鱼18 小时前
Rust 中 package crate 和 module 的关系
rust
Rust研习社19 小时前
Rust 官方拟定 LLM 政策,防止 LLM 污染开源社区?
开发语言·后端·ai·rust·开源
techdashen19 小时前
Async Rust 近况补课:从 `async-trait` 到原生 async trait
网络·算法·rust
techdashen20 小时前
在 Async Rust 中实现请求合并(Request Coalescing)
开发语言·后端·rust
咸甜适中2 天前
rust语言学习笔记Trait(八)Iterator(迭代器)
笔记·学习·rust
zoomdong2 天前
@utoo/pack: 基于 Turbopack 的下一代 Rust 构建工具
webpack·rust·开源
数据法师2 天前
MotrixNext:接棒经典 Motrix,用 Tauri 2+Rust 重构的下一代开源下载神器
重构·rust·开源