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

相关推荐
小灰灰搞电子4 小时前
Rust+Slint 实现FTP客户端调试助手源码分享
开发语言·后端·rust
Flynt5 小时前
Cloudflare 用 Rust 重写了 TypeScript:我拿同一批代码跑了跑,报错一模一样,退出码不一样
rust·typescript·前端工程化
miofly12 小时前
GitHub 今日推荐|pandacode:本地桌面统一管理多个AI编码代理
rust·开源·github
怪我冷i12 小时前
Rust 核心语法与内存安全机制
开发语言·安全·rust
程工造Agent1 天前
从 0 到 1 学 Codex 源码:顺着 main 读懂 Rust 闭包与 async move
rust·ai编程
shimly1234562 天前
(done) RUST 指针详解
rust
geovindu2 天前
rust: Template Method Pattern
开发语言·后端·设计模式·rust·行为模式·模板方法模
遇码2 天前
Rust 桌面应用自托管自动更新:latest.json 清单 + minisign 签名校验的完整做法
人工智能·ai·rust·大模型·agent
geovindu2 天前
rust: Template Method Pattern(续)
开发语言·后端·设计模式·rust·行为模式·板方法模式
niyongsheng2 天前
多智能体连续时间内路径规划:AA-SIPP(m) 的 Rust 实现与算法
算法·rust·机器人