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

相关推荐
techdashen13 小时前
Rust 中的小字符串:smol_str 与 smartstring 的对决
开发语言·后端·rust
福大大架构师每日一题14 小时前
rust 1.96.0 更新:语言、编译器、Cargo、Rustdoc、兼容性全面升级,必看完整解读
android·开发语言·rust
右耳朵猫AI15 小时前
Rust技术周刊 2026年第20周
开发语言·后端·rust
小杍随笔17 小时前
【Rust后端缓存设计实战:从本地moka到Redis多层架构的避坑指南】
redis·缓存·rust
零点一顿微胖17 小时前
[Agent] 初始化Agent服务 Rust版
开发语言·网络·rust
alwaysrun1 天前
Rust之代数数据类型Enum
后端·rust·编程语言
疏狂难除2 天前
随便玩玩lldb(三)
rust·lldb
右耳朵猫AI2 天前
Rust技术周刊 2026年第19周
开发语言·后端·rust
古城小栈2 天前
cargo-pprof:Rust性能调优
人工智能·算法·rust