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

相关推荐
Source.Liu14 小时前
【glam】线性代数库 lib.rs 文件解析
rust·glam
大黄说说14 小时前
Rust 入门到实战:构建安全、高性能的下一代系统
开发语言·安全·rust
好家伙VCC15 小时前
# 发散创新:用 Rust构建高并发虚拟世界引擎核心模块在当今游戏开发与元宇宙构建中,**虚拟世界的性能瓶颈往往不是图形渲染,而是底
java·开发语言·python·rust·图形渲染
Mr -老鬼15 小时前
前后端联调避坑!Vue优先IPv6导致接口不通,Rust Salvo这样解决
前端·vue.js·rust
Source.Liu15 小时前
【glam】断言宏解析
rust·glam
咚为15 小时前
告别 lazy_static:深度解析 Rust OnceCell 的前世今生与实战
开发语言·后端·rust
Java水解1 天前
Rust异步编程实战:构建高性能网络应用
后端·rust
土豆12501 天前
Rust 实战:手把手教你开发一个命令行工具
前端·rust
勇敢牛牛_1 天前
【aiway】基于 Rust 开发的 API + AI 网关
开发语言·后端·网关·ai·rust
Source.Liu2 天前
【Iced】`lib.rs` 源码分析 - `iced_core` 核心库
rust·iced