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

相关推荐
p***434814 小时前
Rust网络编程模型
开发语言·网络·rust
2***656316 小时前
数据库操作与数据管理——Rust 与 SQLite 的集成
数据库·rust·sqlite
q***318319 小时前
Windows安装Rust环境(详细教程)
开发语言·windows·rust
惜棠21 小时前
visual code + rust入门指南
开发语言·后端·rust
n***i9521 小时前
Rust在嵌入式系统中的内存管理
开发语言·后端·rust
7***53341 天前
Rust错误处理模式
开发语言·后端·rust
4***14901 天前
Rust系统工具开发实践指南
开发语言·后端·rust
5***79001 天前
Rust在区块链智能合约中的安全实践
rust·区块链·智能合约
q***d1731 天前
Rust在网络中的协议栈
开发语言·网络·rust
星释1 天前
Rust 练习册 88:OCR Numbers与光学字符识别
开发语言·后端·rust