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

相关推荐
superman超哥21 小时前
Rust `‘static` 生命周期:从字面意义到深层语义
开发语言·后端·rust·生命周期·编程语言·rust static·深层语义
半夏知半秋21 小时前
rust学习-Option与Result
开发语言·笔记·后端·学习·rust
superman超哥1 天前
Rust 结构体中的生命周期参数:所有权设计的核心抉择
开发语言·后端·rust·rust结构体·rust生命周期·所有权设计
lusasky1 天前
在Windows上编译、安装Rust
开发语言·windows·rust
半夏知半秋1 天前
rust学习-探讨为什么需要标注生命周期
开发语言·笔记·学习·算法·rust
superman超哥1 天前
Rust 生命周期边界:约束系统的精确表达
开发语言·后端·rust·rust生命周期边界·约束系统
superman超哥1 天前
Rust 生命周期省略规则:编译器的智能推导机制
开发语言·后端·rust·编译器·rust生命周期·省略规则·智能推导
xuejianxinokok1 天前
rust trait 相比于传统的 oop 有哪些优点?
后端·rust
superman超哥1 天前
Rust Rc与Arc的引用计数机制:共享所有权的两种实现
开发语言·后端·rust·编程语言·rust rc与arc·引用计数机制·共享所有权