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

相关推荐
superman超哥3 小时前
Rust 异步时间管理核心:Tokio 定时器实现机制深度剖析
开发语言·rust·编程语言·rust异步时间管理核心·tokio定时器实现机制·tokio定时器
古城小栈3 小时前
Rust 的 validator 库
开发语言·后端·rust
古城小栈3 小时前
Rust 的 redis-rs 库
开发语言·redis·rust
superman超哥4 小时前
Rust 异步递归的解决方案
开发语言·后端·rust·编程语言·rust异步递归
Mr -老鬼5 小时前
Rust 的优雅和其他语言的不同之处
java·开发语言·rust
weixin_531651815 小时前
Rust 的所有权机制
java·开发语言·rust
古城小栈7 小时前
Rust 丰富&好用的 格式化语法
前端·算法·rust
古城小栈9 小时前
Tokio:Rust 异步界的 “霸主”
开发语言·后端·rust
superman超哥10 小时前
Rust 异步并发核心:tokio::spawn 与任务派发机制深度解析
开发语言·rust·编程语言·rust异步并发核心·rust任务派发机制
木木木一10 小时前
Rust学习记录--C9 错误处理
前端·学习·rust