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

相关推荐
魔镜前的帅比3 小时前
(开源项目)x-claw(总)
python·ai·rust·开源
Source.Liu8 小时前
【Uppsala】入口模块(lib.rs)
xml·rust
SomeB1oody8 小时前
【RustyML入门】2.6. 线性判别分析
开发语言·后端·机器学习·rust·教程
魔镜前的帅比11 小时前
(开源项目)x-claw (设计)
python·ai·rust·开源
Cicada12811 小时前
ccvt:一个用 Rust 写的中国地图坐标系互转命令行工具
开发语言·后端·rust
Source.Liu12 小时前
【Uppsala】介绍
xml·rust
程序员爱钓鱼17 小时前
Rust Clone详解:深拷贝、复制成本与正确使用方式
后端·面试·rust
seacracker17 小时前
一个 Rust 写的存储系统,想把 HPC 和 AI 的存储栈统一了
开发语言·人工智能·rust
lanfordxb1 天前
从 Markdown 到图片卡片:MarkCard Studio 的功能设计与官网实现记录
rust·软件工程·ai工具
yiqiefeimeng1 天前
Rust还是Go?编程语言的未来之争
rust·go·编程语言·技术社区·未来之争