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

相关推荐
Ivanqhz2 小时前
半格与数据流分析的五个要素(D、V、F、I、Λ)
开发语言·c++·后端·算法·rust
Ivanqhz8 小时前
数据流分析的核心格(Lattice)系统
开发语言·javascript·后端·python·算法·蓝桥杯·rust
键盘鼓手苏苏8 小时前
Flutter for OpenHarmony 实战:Flutter Rust Bridge — 极致计算性能方案
开发语言·后端·flutter·华为·rust·json·harmonyos
❀͜͡傀儡师10 小时前
DragonOS ——基于Rust自研内核的国产新星操作系统
rust·dragonos
古城小栈10 小时前
Rust 中的 内存对齐
开发语言·后端·rust
Mr -老鬼11 小时前
从 0 到 1 落地:Rust + Salvo 实现用户系统与 Bug 管理系统
开发语言·rust·bug
班公湖里洗过脚1 天前
《通过例子学 Rust》第15章 作用域规则
rust
班公湖里洗过脚1 天前
《通过例子学Rust》第12章 cargo
rust
古城小栈1 天前
Rust中 引用类型 VS 裸指针
开发语言·后端·rust
班公湖里洗过脚2 天前
《通过例子学Rust》第13章 属性
rust