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

相关推荐
yezipi耶不耶8 小时前
Rust入门之并发编程基础(三)
rust
SoniaChen3319 小时前
Rust基础[part4]_基本类型,所有权
开发语言·后端·rust
will_csdn_go19 小时前
祺洛后台管理 Rust Cross 交叉编译环境配置指南
开发语言·后端·rust
Source.Liu20 小时前
【unitrix】 6.5 基础整数类型特征(base_int.rs)
rust
PaytonD20 小时前
基于 iced 实现一个简易时钟
rust
Humbunklung1 天前
Rust 模块系统:控制作用域与私有性
开发语言·后端·rust
毒鸡蛋2 天前
Rust 基础大纲
rust
songroom2 天前
【转】Rust: PhantomData,#may_dangle和Drop Check 真真假假
开发语言·后端·rust
红尘散仙2 天前
Rust 终端 UI 开发新玩法:用 Ratatui Kit 轻松打造高颜值 CLI
前端·后端·rust
我是前端小学生3 天前
solana_business_card合约解析
rust