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

相关推荐
k4m7v2pz2 分钟前
把 Bevy 0.14 游戏移植到 R36S 掌机:一场与“无窗口系统“的搏斗
linux·rust·bevy·r36s·rk3326·开源掌机
doiito1 小时前
【Agent Harness】流马(Gliding Horse)DeepSeek Responses API 接入介绍
rust·系统设计·ai agent
SomeB1oody7 小时前
【RustyML入门】2.0. 经典机器学习
开发语言·后端·机器学习·rust·教程
Embedded-Xin7 小时前
Rust学习——Cargo工具
linux·学习·架构·rust·嵌入式
龙仔7258 小时前
RustDesk 完整笔记
运维·笔记·rust·远程工具·rustdesk
An_s9 小时前
rust(pdfium)底层开发实现wasm包给vue3调用
开发语言·rust·wasm
对象存储与RustFS12 小时前
为什么越来越多的企业选择RustFS作为对象存储?
后端·rust·开源
KryptonWright1 天前
让 AI Agent 只能提议、不能擅自执行:Rust 中 prepare-confirm-execute 权限模型的实现
rust
起司喵喵1 天前
推荐一款基于 Python 和 Rust 开发的跨平台 GUI 自动化库!
python·rust·自动化
花褪残红青杏小2 天前
Rust图像处理第24节- 噪声模型 + 中心极限定理:椒盐噪声 + CLT 可视化
rust·webassembly·图形学