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

相关推荐
问道飞鱼1 天前
【Tauri框架学习】Tauri 与 React 前端集成:通信机制与交互原理详解
前端·学习·react.js·rust·通信
weixin_387534222 天前
Ownership - Rust Hardcore Head to Toe
开发语言·后端·算法·rust
luffy54592 天前
Rust语言入门-变量篇
开发语言·后端·rust
好家伙VCC2 天前
# 发散创新:用 Rust构建高性能游戏日系统,从零实现事件驱动架构 在现代游戏开发中,**性能与可扩展性**是核心命题。传统基于
java·python·游戏·架构·rust
Source.Liu2 天前
【Iced】transformation.rs文件解析
rust·iced
小杍随笔2 天前
【Rust 语言编程知识与应用:闭包详解】
开发语言·后端·rust
Ivanqhz2 天前
图着色寄存器分配算法(Graph Coloring)
开发语言·javascript·python·算法·蓝桥杯·rust
42tr_k3 天前
Rust LanceDB 内存不足问题
rust
Source.Liu3 天前
【Iced】benches 文件夹分析笔记
rust·iced
Source.Liu3 天前
【glam】线性代数库 lib.rs 文件解析
rust·glam