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

相关推荐
班公湖里洗过脚11 分钟前
Rust操作Josn数据及工作目录下多个应用程序维护示例
rust
Source.Liu3 小时前
【rust-i18n】readme.md文件
rust·rust-i18n
锅包一切21 小时前
在蓝桥杯边练边学Rust:2.原生类型
开发语言·学习·蓝桥杯·rust
@atweiwei1 天前
Rust 实现 LangChain
开发语言·算法·rust·langchain·llm·agent·rag
Hello.Reader1 天前
Tauri 开发环境 Prerequisites 桌面 + 移动端)
rust·tauri
Source.Liu1 天前
【rust-i18n】简介
rust·rust-i18n
鸿乃江边鸟1 天前
Spark Datafusion Comet 向量化Rust Native--Native算子ScanExec以及涉及到的Selection Vectors
大数据·rust·spark·arrow
Hello.Reader1 天前
Tauri 用“系统 WebView + 原生能力”构建更小更快的跨平台应用
rust·tauri
RoyLin2 天前
Rust 编写的 40MB 大小 MicroVM 运行时,完美替代 Docker 作为 AI Agent Sandbox
后端·架构·rust
班公湖里洗过脚2 天前
《通过例子学Rust》第20章 标准库更多介绍
rust