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

相关推荐
wflynn10 小时前
GitHub 今日推荐|Stela:在 PC 上直接启动 macOS 的翻译层
rust·开源·github
aifannihao12 小时前
Rust 1.100 的 DropGuard:用 Python 实测失败回滚与吞异常
python·rust·异常处理·标准库·contextlib
鶴哥只手遮天18 小时前
《rustc 内幕》第 1 章 全景:rustc 编译流水线与 crate 版图
后端·rust·开源
SomeOtherTime2 天前
Rust 闭包语法和原理(AI回答)
开发语言·后端·rust
SomeOtherTime2 天前
Rust集合(AI回答)
开发语言·后端·rust
SomeOtherTime2 天前
Rust 泛型与特性讲解(AI回答)
rust
青川Lapis3 天前
RUST:错误处理 thiserror + anyhow 工程化
rust
SomeOtherTime3 天前
Rust生命周期介绍(AI回答)
开发语言·后端·rust
SomeOtherTime3 天前
Rust所有权(AI回答)
开发语言·后端·rust
SomeOtherTime4 天前
Rust 面向对象介绍(AI回答)
开发语言·python·rust