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

相关推荐
geovindu14 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
喵个咪15 小时前
RushWind Admin — 模块化单体:一个进程与通往微服务的五级阶梯
后端·架构·rust
喵个咪16 小时前
RushWind CMS — 最小微服务实例:微服务架构的最小完备集
后端·架构·rust
geovindu2 天前
rust: Timing Functions Pattern
开发语言·后端·设计模式·rust·计时函数模式·性能分析型模式
关键词安全2 天前
PHP / Node.js / Go / Rust 全部中招(CVE-2026-109618、109619、111497、111943)完整排查与修复清单
golang·rust·node.js
xjz18423 天前
Rust 的`+=`、`-=`、`*=`、`/=` —— 让变量更新更简洁
rust
xjz18424 天前
Rust 用 `&&`、`||`、`!` 把条件组合起来
rust
不积跬步无以至千里mmbb264 天前
Rust三大核心:Trait Crate Mod详解
linux·rust
SomeOtherTime4 天前
第 2 讲:借用检查器(Borrow Checker)的数学本质——读写锁的编译期化、非词法生命周期(NLL)与重借用(Reborrowing)
rust
xjz18425 天前
Rust 的else:把「做不做」升级成「二选一」
rust