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

相关推荐
Source.Liu1 天前
【Rust】方法重载
rust
QC七哥1 天前
基于tauri构建全平台应用
rust·electron·nodejs·tauri
wadesir1 天前
Rust中的条件变量详解(使用Condvar的wait方法实现线程同步)
开发语言·算法·rust
hans汉斯1 天前
嵌入式操作系统技术发展趋势
大数据·数据库·物联网·rust·云计算·嵌入式实时数据库·汉斯出版社
Source.Liu2 天前
【Rust】布尔类型详解
rust
清醒的土土土2 天前
Tokio 源码学习01——Mutex
rust
分布式存储与RustFS2 天前
实测!Windows环境下RustFS的安装与避坑指南
人工智能·windows·rust·对象存储·企业存储·rustfs
唐装鼠2 天前
rust AsRef 和 AsMut(deepseek)
rust
唐装鼠2 天前
Rust Cow(deepseek)
开发语言·后端·rust
Source.Liu2 天前
【Rust】分支语句详解
rust