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

相关推荐
没逻辑4 小时前
高性能计算的利器:Rust中的SIMD实战指南
后端·rust
盒马盒马5 小时前
Rust:复合类型
开发语言·rust
摘星编程8 小时前
深入 Actix-web 源码:解密 Rust Web 框架的高性能内核
开发语言·前端·rust·actixweb
Momentary_SixthSense10 小时前
rust笔记
开发语言·笔记·rust
lpfasd12311 小时前
从 Electron 转向 Tauri:用 Rust 打造更轻、更快的桌面应用
javascript·rust·electron
RustCoder13 小时前
基于 Rust 的 Rustls 性能优于 OpenSSL 和 BoringSSL
物联网·安全·rust
努力进修15 小时前
Rust 语言入门基础教程:从环境搭建到 Cargo 工具链
开发语言·后端·rust
ai安歌1 天前
【Rust编程:从新手到大师】Rust变量深度详解
rust
G_dou_1 天前
智能指针完全指南
windows·rust
G_dou_1 天前
并发编程基础
算法·rust