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 小时前
tokei 在鸿蒙PC上的构建与适配
后端·华为·rust·harmonyos
疏狂难除5 小时前
尝试rust与python的混合编程(一)
开发语言·后端·python·rust
H***997611 小时前
Rust在WebAssembly中的使用
开发语言·rust·wasm
百锦再11 小时前
[特殊字符] HBuilder uni-app UI 组件库全方位对比
android·java·开发语言·ui·rust·uni-app·go
q***d17315 小时前
Rust并发模型
开发语言·后端·rust
q***483118 小时前
数据库操作与数据管理——Rust 与 SQLite 的集成
数据库·rust·sqlite
Andrew_Ryan1 天前
达梦 数据库 Rust 实战
数据库·rust·数据分析
桧***攮1 天前
DockerGraphQLAPI
elementui·rust·visual studio
CNRio1 天前
ZUC国密算法深度研究:原理、实现与应用(Python、Rust)
python·算法·rust
勤奋的小小尘1 天前
第十篇:Rust 错误处理
rust