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

相关推荐
红尘散仙6 小时前
一套 Rust 核心,跑通 Tauri + React Native
react native·react.js·rust
feasibility.6 小时前
反爬十层妖塔:现代爬虫攻防的立体战争
爬虫·python·科技·scrapy·rust·go·硬件
王木风8 小时前
终端里的编程副驾:DeepSeek-TUI-项目深度拆解,实测与原理分析
linux·运维·人工智能·rust·node.js
迷渡10 小时前
聊一聊 Bun 用 Rust 重写这件事
开发语言·后端·rust
RustCoder11 小时前
MangoFetch:一个用 Rust 写的 CLI/TUI 高性能的下载工具
后端·rust·开源
fox_lht16 小时前
第十二章 泛型、接口和生命周期
开发语言·后端·rust
小杍随笔16 小时前
【iNovel 后端架构深度解析:基于 Rust + Tauri 2 的桌面应用服务端设计】
jvm·架构·rust
小杍随笔16 小时前
Axum+Leptos全栈集成实战
开发语言·后端·架构·rust
咸甜适中17 小时前
rust语言学习笔记Trait之 From 和 Into (类型转换)
笔记·学习·rust
techdashen17 小时前
Rust 社区在 4 月做了什么:项目管理月报解读
开发语言·rust·mfc