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

相关推荐
l1t8 小时前
DeepSeek总结的将 Rust Delta Kernel 集成到 ClickHouse
数据库·clickhouse·rust
techdashen10 小时前
在 Rust 异步接口的丛林中生存:从同步 I/O 到手写异步状态机
开发语言·后端·rust
guyoung10 小时前
BoxAgnts介绍(1)——开箱即用(Out-Of-The-Box)
rust·agent·ai编程
斐夷所非11 小时前
从 Oxidizr 到 Oxidizer | Rust 在系统与逆向工程的应用
rust
星栈独行16 小时前
别让 API 跳去登录页:我在 Axum 里做了认证失败双通道
前端·后端·rust·开源·github·个人开发
古城小栈1 天前
Rust 调用 C 语言库 实战指南(企业级)
c语言·开发语言·rust
刘布斯yy1 天前
新写了个直播录制工具,可录制抖音快手斗鱼直播
rust·音视频·直播录制
恋喵大鲤鱼2 天前
Rust 中的字符串 slice 是什么?
rust
迷渡2 天前
用 Rust 重写的 Bun 有 13365 个 unsafe!
开发语言·后端·rust
咸甜适中2 天前
rust语言学习笔记Trait(九)PartialEq、 Eq(相等比较)
笔记·学习·rust