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

相关推荐
落知秋8 小时前
RUST中的trait是什么?
笔记·rust
Embedded-Xin14 小时前
中间件—zenoh零基础入门
linux·中间件·rust·机器人·自动驾驶·嵌入式
程序员爱钓鱼17 小时前
Rust 可变借用详解:&mut T 与安全修改数据
后端·面试·rust
SomeB1oody1 天前
【RustyML入门】2.9. MeanShift
开发语言·后端·机器学习·rust·教程
SomeB1oody2 天前
【RustyML入门】2.10. 主成分分析
开发语言·后端·机器学习·rust·教程
yushikong2 天前
关于rust开发ch32x033f8p6的一些记录
开发语言·后端·rust
程序员爱钓鱼2 天前
Rust Borrow借用详解:不转移所有权访问数据
后端·面试·rust
程序员爱钓鱼2 天前
Rust Copy详解:隐式复制与轻量数据类型
前端·后端·rust
kaixin_learn_qt_ing2 天前
了解Rust/Tauri
rust