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

相关推荐
web前端进阶者2 小时前
Rust初学知识点快速记忆
开发语言·后端·rust
一只幸运猫.6 小时前
Rust实用工具特型-Clone
开发语言·后端·rust
咚为6 小时前
深入浅出 Rust 内存顺序:从 CPU 重排到 Atomic Ordering
开发语言·后端·rust
咚为8 小时前
深入浅出 Rust RefCell:打破静态检查的“紧箍咒”
开发语言·后端·rust
lUie INGA1 天前
rust web框架actix和axum比较
前端·人工智能·rust
沛沛rh451 天前
深入并发编程:从 C++ 到 Rust 的学习笔记
c++·笔记·学习·算法·rust
沛沛rh451 天前
力扣 42. 接雨水 - 高效双指针解法(Rust实现)详细题解
算法·leetcode·rust
pan3035074791 天前
在 Vue 3 + Vite 项目中覆盖 Element Plus 的默认样式
前端·vue.js·rust
Rust研习社1 天前
Rust 的构建脚本是什么?今天一次性搞懂它
rust
向上的车轮2 天前
从零实现一个高性能 HTTP 服务器:深入理解 Tokio 异步运行时与 Pin 机制
rust·系统编程·pin·异步编程·tokio·http服务器