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

相关推荐
怪我冷i13 小时前
Rust 智能指针 RefCell<T> 与内部可变性模式
rust
YOLOW9217 小时前
两周五个版本:我用 Rust 写的 AI 数据引擎 PageSift,0.81 系列做了什么
rust
西风测评17 小时前
SSH 中文乱码的根源:locale、SendEnv 与 env 请求
rust
unconditional17 小时前
我数了下 sdkm 的源码:41 个工具的安装逻辑,四分之三是同一行
rust·开源
niyongsheng1 天前
3D 装箱算法工程化:数据结构、放置启发式与支撑规则
数据结构·算法·rust
Hello.Reader1 天前
tsrs 技术解析用 Rust 移植 TypeScript 7,类型检查还能怎样提速?
开发语言·rust·typescript
王仔小奶2 天前
Rust 正在接管金融圈?深度拆解一份高薪 FinTech 岗位 JD
开发语言·金融·rust
你为她披上外套时我正站在窗外2 天前
subtitler v2.10 发布:3 个社区 PR、一个一天修掉的 issue,和关于 uuencode 的真相
rust
Thneonl2 天前
熔断不是开关是状态机:Claude Code 路由内核的 3 条红线
人工智能·rust
Thneonl2 天前
一个 Claude Code 本地代理,凭啥配了 3 个观测出口?
人工智能·rust