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

相关推荐
古城小栈1 天前
Rust 泛型 敲黑板
rust
古城小栈1 天前
Rust Trait 敲黑板
开发语言·rust
浪客川1 天前
【百例RUST - 005】所有权和切片
开发语言·后端·rust
古城小栈1 天前
Axum: Rust 好用的 Web 框架
开发语言·rust
古城小栈1 天前
Rust 并发、异步,碾碎它们
开发语言·后端·rust
木木木一1 天前
Rust学习记录--C8 常用的集合
开发语言·学习·rust
TDengine (老段)1 天前
TDengine Rust 连接器入门指南
大数据·数据库·物联网·rust·时序数据库·tdengine·涛思数据
Kapaseker1 天前
来自 Rust 官网的王婆卖瓜
rust
鲁正杰2 天前
【运维部署】现代化内网穿透与文件共享方案 (Rust)
运维·开发语言·rust