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.Liu16 小时前
【Rust】函数
rust
huatian516 小时前
Rust 语法整理
开发语言·后端·rust
九月生20 小时前
Rust CLI 项目构建指南
rust
徐安安ye21 小时前
Flutter 与 Rust 混合开发:打造毫秒级响应的高性能计算引擎
开发语言·flutter·rust
浪客川21 小时前
rust入门案例-猜数字游戏
开发语言·rust
Source.Liu1 天前
【Rust】方法
rust
Source.Liu1 天前
【Rust】if表达式详解
rust
Source.Liu1 天前
【Rust】循环控制结构
rust
Source.Liu1 天前
【Rust】元组:轻量级数据组合利器
rust
RustFS2 天前
RustFS 如何实现对象存储的前端直传?
vue.js·docker·rust