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

相关推荐
蒜香可达鸭13 小时前
Grok-build: Rust 工程实践分析
rust
SomeB1oody17 小时前
【RustyML入门】5.2. 分类指标
开发语言·后端·机器学习·rust·教程
星栈20 小时前
被 Rust async 纠正的三个异步认知
前端·后端·rust
smallswan20 小时前
《Rust七十二变》开源了
开发语言·后端·rust·ai编程
深海呐1 天前
Rust 语言完整解读
java·开发语言·rust
SomeB1oody1 天前
【RustyML入门】5.1. 回归指标
开发语言·后端·机器学习·rust·教程
程序员爱钓鱼1 天前
Rust Trait详解:定义共享行为与抽象接口
后端·面试·rust
SomeB1oody2 天前
【RustyML入门】5.0. 模型评估
开发语言·后端·机器学习·rust·教程
今天AI了吗2 天前
Agent & AI 名词大扫盲
数据库·人工智能·python·sql·rust
SomeB1oody3 天前
【RustyML入门】4.2. 标准化与归一化
开发语言·后端·机器学习·rust·教程