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

相关推荐
Amos_Web15 分钟前
Rspack 源码解析(十二):JavaScript Chunk 是如何被渲染出来的
前端·rust·源码
柯南466822 分钟前
【AI开发之Rust】第 14 课:网络请求与 JSON —— reqwest + serde
rust·编程语言
恋喵大鲤鱼1 小时前
Rust 格式化输出占位符详解
rust
孙启超2 小时前
【AI开发之Rust】第 13 课:async/await 与 tokio 异步运行时
开发语言·后端·rust
小道士写程序2 小时前
Rust + Axum + MySQL + SQLx
rust
mikuyyds19 小时前
geo-toolbox 插件算法解析:RUSLE 与 MUSLE 的工程化落地
算法·rust·gis
qq_4523962320 小时前
第十四篇:《系统编程实战:用 Rust 编写高性能 HTTP 服务器》
rust
Amos_Web1 天前
Rspack 源码解析(十一):资产 Hook 与增量构建
前端·rust·源码阅读
孙启超1 天前
【AI开发之Rust】第 12 课:并发模型与同步原语
开发语言·后端·rust