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

相关推荐
wadesir19 小时前
深入理解Rust静态生命周期(从零开始掌握‘static的奥秘)
开发语言·后端·rust
脑极体1 天前
蓝河入海:Rust先行者vivo的开源之志
开发语言·后端·rust·开源
badmonster01 天前
实时代码库索引:用 CocoIndex 构建智能代码搜索的终极方案
python·rust
黛色正浓1 天前
【React】极客园案例实践-项目搭建和登录模块
前端·react.js·rust
思密吗喽1 天前
npm install 报错,解决 node-sass@4.14.1 安装失败问题
rust·npm·node.js·毕业设计·sass·课程设计
青云交1 天前
深度实战:Rust交叉编译适配OpenHarmony PC——ansi_term完整适配案例
rust·交叉编译·命令行工具·openharmony pc·ansi_term·适配案例·终端颜色
星释1 天前
Rust 练习册 106:太空年龄计算器与宏的魔法
开发语言·后端·rust
ALex_zry1 天前
系统编程的基石:补码循环溢出与Rust变量绑定的深度探索
开发语言·后端·rust
ALex_zry1 天前
Rust语言基础分析与C++对比:系统编程的现代演进
java·c++·rust
星释1 天前
Rust 练习册 105:从零开始实现链表数据结构
数据结构·链表·rust