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.Liu3 小时前
【A11】Duration —— 精确时长结构体实现
rust·time
右耳朵猫AI_5 小时前
用 Rust 重写 Bun
rust·bun
独孤留白5 小时前
Rust 可变性完整指南 —— 从默认不可变到多线程安全修改
rust
hsg7712 小时前
简述:Rust、GeoRust、自主研发GIS平台
开发语言·后端·rust
AOwhisky1 天前
下一代容器来了?Docker 宣布原生支持 WebAssembly
java·运维·docker·容器·rust·wasm
铅笔侠_小龙虾1 天前
Rust 学习(6)-所有权规则、移动语义、Clone 与 Copy
python·学习·rust
程序员爱钓鱼1 天前
Rust 控制流 if 详解:条件判断与 if 表达式
前端·后端·rust
花褪残红青杏小2 天前
Rust图像处理第19节-RGB 色彩矩阵变换:矩阵 × 向量 = 像素变换
rust·webassembly·图形学
white_ant2 天前
15-ASCII 转换工具使用指南
rust·tauri·watools
铅笔侠_小龙虾2 天前
Rust 学习(2)-变量、常量与 shadowing
学习·算法·rust