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

相关推荐
k4m7v2pz4 小时前
rvs(rust-verb-shell):一款面向人类和 AI Agent 的结构化 Shell
rust·shell·基建·rust-verb-shell·verb-noun
CappuccinoRose11 小时前
Rust学习文档(二)
开发语言·后端·学习·rust
Ivanqhz12 小时前
Rust 自引用结构(Self-Referential Structure)
rust
Yeauty13 小时前
你那条 ffmpeg 命令,一键翻成 Rust builder 代码
开发语言·rust·ffmpeg
程序员爱钓鱼13 小时前
Rust Option 详解:安全处理“可能存在,也可能不存在”的值
前端·后端·rust
带娃的IT创业者1 天前
重新定义前端构建速度:深度解析 SWC 如何用 Rust 颠覆 JavaScript 工具链
前端·javascript·rust·前端构建·swc
Yeauty2 天前
用 Whisper 转录前,你不用再离开 Rust
开发语言·rust·ffmpeg·音视频·视频
程序员爱钓鱼2 天前
Rust HashMap 详解:键值存储、查询、更新与统计
后端·面试·rust
doiito2 天前
【AI 应用】从“外国人味”到地道中文:kokoroi-rs v0.1.2 架构升级深度解析
ai·rust·系统设计
Zwarwolf2 天前
Rust零散知识点项目汇总
开发语言·rust