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

相关推荐
红尘散仙10 小时前
浏览器不能监听端口、没有文件系统,凭什么能点对点传文件?
rust·webrtc·webassembly
nnerddboy12 小时前
Rust教程06:ESP32-rust环境搭建
开发语言·后端·rust
nnerddboy12 小时前
Rust教程03:函数,控制流与所有权
开发语言·后端·rust
nnerddboy13 小时前
Rust教程05:结构体,枚举与模式匹配
开发语言·网络·rust
特立独行的猫a16 小时前
我用 Rust + Tauri 2 复刻了 N_m3u8DL-CLI:一个 m3u8 多线程下载器
开发语言·后端·rust·m3u8·视频下载器·m3u8dl-cli
对象存储与RustFS16 小时前
大文件传到 48 GiB 就断:S3 分片上传的参数怎么算,以及那些没人清的残片
后端·rust·开源
程序员爱钓鱼18 小时前
Rust 生命周期案例详解:从编译错误到真实业务场景
前端·后端·rust
Albart5752 天前
【玩转 AtomCode】替代Claude Code!开源多模型免费AI编码Agent深度实测教程
人工智能·rust·开源·atomcode·多模型ai
特立独行的猫A2 天前
Rust+Tauri 2实现个人聚藏APP:一个 “注定上不了“ 的个人收藏夹
rust
jeffwang2 天前
我把同一个压测做错了三次,第四次才发现真正的瓶颈
分布式·性能优化·rust