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

相关推荐
Yunovian2 小时前
AI时代,针对模型与应用,浅谈一下各编程语言
开发语言·c++·人工智能·python·ai·rust·ai编程
Kapaseker4 小时前
Rust 凭什么不用垃圾回收?先搞懂 Owner
rust
Amos_Web5 小时前
Rspack 源码解析(十五):Loader Runner 与 JS Loader 桥接
前端·rust·前端框架
柯南466812 小时前
【AI开发之Rust】第 18 课:SQLite 持久化与本地缓存 —— 给 store 填上真实现
rust·编程语言
柯南466812 小时前
【AI开发之Rust】第 17 课:项目总览与核心架构 —— AI 助手 Rust 核心从 0 到 1
rust·编程语言
柯南466812 小时前
【AI开发之Rust】第 16 课:FFI 手写绑定与内存布局 —— 把 Rust 交给别的语言
rust·编程语言
达子66612 小时前
RUST 图解 第 2 章:写小游戏
rust
Amos_Web12 小时前
Rspack 源码解析(十四):Resolver 与 NormalModuleFactory
前端·rust·源码
Kapaseker12 小时前
秒懂 Rust 的 7 个核心概念
rust
RobinDevNotes12 小时前
用 godot-rust 给 Godot 写 Rust 扩展
rust·游戏开发