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

相关推荐
gopher951113 小时前
RUST:序列化与反序列化 serde + derive 详解
开发语言·后端·rust
遇码1 天前
流式调用中途断连别直接报错:瞬态故障识别、退避重试与中文根因诊断的搭建方法
大数据·人工智能·ai·rust·数据分析·大模型·agent
DongQiShanRen1 天前
六根硬件映射(四):归属澄清、两处不一致与卷十一总表
开发语言·人工智能·算法·rust·哈希算法·集成学习
alwaysrun1 天前
Web之wasm-pack详解
前端·rust·web·wasm
DongQiShanRen1 天前
六根硬件映射(下):物理闭环五步法,抽一条已实装的看
大数据·jvm·人工智能·算法·rust·哈希算法·集成学习
Zenova EdgeOS1 天前
Rust TUI 实战:用 ratatui 构建工业边缘终端界面
开发语言·后端·rust·工业网关
遇码2 天前
不用转场引擎做幻灯片转场:相机滑动、黑场淡入与真全屏的完整做法
人工智能·数码相机·ai·rust·大模型·agent
lpfasd1232 天前
node-sass 停止维护!老项目迁移 Dart Sass 完整教程
前端·rust·sass
Flynt2 天前
我把真实的 ES 查询怼到 7059 星的 Rust 搜索引擎上:1366/1369 的兼容承诺,裂了 3 个缝
elasticsearch·搜索引擎·rust
小杍随笔2 天前
egui 0.37 升级实录:卡顿修复与5倍性能回退
windows·rust·egui