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

相关推荐
Mintopia6 小时前
⚙️ 模型接口与微调兼容性:AIGC系统整合的底层心脏跳动
人工智能·架构·rust
ULTRA??6 小时前
RUST是移动语义与copy trait
算法·rust
Source.Liu6 小时前
【time-rs】编译器优化提示模块详解
rust·time
Source.Liu7 小时前
【time-rs】time-core 中的 convert.rs 文件详解
rust·time
星释1 天前
Rust 练习册 120:探索向量与斐波那契数列
开发语言·后端·rust
gregmankiw1 天前
Rust错误处理
rust
勇敢牛牛_1 天前
【aiway】一个Rust实现的API网关
rust·api网关
朝阳5811 天前
Rust 并行压缩如何改变我的工作流程
后端·rust
muyouking111 天前
Zig 模块系统详解:从文件到命名空间,与 Rust 的模块哲学对比
开发语言·后端·rust
muyouking111 天前
Zig vs Rust:常用类型声明方式对比与核心理念解析
rust