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

相关推荐
Patrick_Wilson9 小时前
sccache 用在 Rust 上为什么常「不省编译」:原理、限制与 Windows 接入
ci/cd·rust·编译器
k4m7v2pz16 小时前
rvs 26.8.43 → 26.8.53 更新概览:MCP 落地、审计增强与谬误澄清
rust·repl·mcp server·rust-verb-shell·rvs·shell 工具
程序员爱钓鱼17 小时前
Rust impl详解:为Struct定义方法与关联函数
前端·后端·rust
k4m7v2pz17 小时前
Rust 程序在 ReactOS 上“加载即崩“:从崩溃地址 0x6107104d 到 CRT 依赖的深度排查
rust·交叉编译·逆向工程·reactos·pe格式·windows兼容
Thneonl1 天前
一个人从 Rust 内核做到 React 前端:我做了一个云原生 SRE 巡检图谱桌面工具
rust
程序员爱钓鱼1 天前
Rust Struct结构体详解:定义自己的复杂数据类型
后端·面试·rust
苏灿烤鱼1 天前
公司**不可计算,就自己做操作系统
rust·typescript·agent
nnerddboy2 天前
Rust教程04:引用、借用与切片
开发语言·后端·rust
咸甜适中2 天前
rust语言AI编程学习笔记(五)clap命令行参数解析
学习·rust·ai编程
梦醒沉醉2 天前
19、Rust程序设计语言——高级特性
rust