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

相关推荐
受之以蒙5 小时前
Rust 与 dora-rs:吃透核心概念,手把手打造跨语言的机器人实时数据流应用
人工智能·笔记·rust
csdn_life1816 小时前
Rustrover 如何像Java一样直接 进行调试和运行
java·开发语言·rust
Source.Liu1 天前
【time-rs】Date 结构体详解
rust·time
qq_256247051 天前
Rust 模块化单体架构:告别全局 Migrations,实现真正的模块自治
开发语言·架构·rust
分布式存储与RustFS1 天前
MinIO替代方案与团队适配性分析:RustFS如何匹配不同规模团队?
人工智能·rust·开源项目·对象存储·minio·企业存储·rustfs
分布式存储与RustFS1 天前
MinIO替代方案生态集成指南:RustFS如何无缝融入现代技术栈
rust·github·开源项目·对象存储·minio·企业存储·rustfs
王燕龙(大卫)1 天前
rust:线程
开发语言·rust
李广坤1 天前
Rust基本使用
后端·rust
Source.Liu2 天前
【time-rs】Duration 结构体详解
rust·time
Chen--Xing2 天前
LeetCode 49.字母异位词分组
c++·python·算法·leetcode·rust