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

相关推荐
itmigrate10 小时前
Rust 里的所有权误区:不是不写 clone 就叫高性能
开发语言·后端·rust
小灰灰搞电子15 小时前
Rust+Slint 实现动态流光边框源码分享
开发语言·前端·rust·流光边框
Bigger15 小时前
开源了一个"先预览、能反悔"的文件整理工具,聊聊背后的工程细节
rust·开源·app
老王IT16 小时前
Rust开发环境搭建教程
开发语言·后端·rust
@大迁世界1 天前
告别 Go,拥抱 Rust
开发语言·golang·rust
低调滴开发1 天前
3 行代码写崩一个函数?切片才是 Rust 字符串处理的正确姿势
开发语言·后端·rust
小灰灰搞电子2 天前
Rust+Slint 实现高级动态消息提示框源码分享
开发语言·rust
qq_406981032 天前
大白话rust系列08 当变量遮蔽遇上引用,探究变量遮蔽的本质
开发语言·后端·rust
轻舟技术A2 天前
Pi、rpi、Pi-Bolt 重测:rpi 在启动、内存与读取上全面领先
人工智能·rust
用户14498433464752 天前
我为什么做一个开源的 Mac 清理工具
rust