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

相关推荐
SomeOtherTime7 小时前
Rust所有权(AI回答)
开发语言·后端·rust
SomeOtherTime17 小时前
Rust 面向对象介绍(AI回答)
开发语言·python·rust
西风测评2 天前
安全的自动更新怎么做:minisign 签名、先验签后解析与防回滚
rust·ssh
Delightrs2 天前
Rust LeetCode238 算法题解
开发语言·算法·rust
奶油话梅糖2 天前
快过 IDM 5 倍、开源免费:4,200 Star 的 Rust 下载器用 7 组对照实验“单挑“行业老大
rust·开源·idm
Zan2 天前
Tauri 2 实战:为什么一个可靠的桌面应用,应该由 Rust Host 管理生命周期?
前端·架构·rust
RobinDevNotes3 天前
从 Electron 到 GPUI,9 个跨平台桌面方案该怎么选
前端·javascript·rust·electron·openresty·前端开发工具
灿飞屋3 天前
Rust 编程其实很简单
开发语言·rust
蔡少将3 天前
用 Tauri 2 给 Mac 应用接 Touch ID,签名公证都做了,还是 -34018
rust
木子欢儿4 天前
国内 macOS/Linux 安装 rust
linux·运维·服务器·macos·rust