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

相关推荐
shimly1234563 小时前
(done) 速通 rustlings(20) 错误处理1 --- 不涉及Traits
rust
shimly1234563 小时前
(done) 速通 rustlings(19) Option
rust
@atweiwei3 小时前
rust所有权机制详解
开发语言·数据结构·后端·rust·内存·所有权
shimly1234563 小时前
(done) 速通 rustlings(24) 错误处理2 --- 涉及Traits
rust
shimly1234564 小时前
(done) 速通 rustlings(23) 特性 Traits
rust
shimly1234565 小时前
(done) 速通 rustlings(17) 哈希表
rust
shimly1234565 小时前
(done) 速通 rustlings(15) 字符串
rust
shimly1234566 小时前
(done) 速通 rustlings(22) 泛型
rust
yezipi耶不耶7 小时前
我在 RTMate 里使用的高并发连接管理利器: DashMap
websocket·rust
初恋叫萱萱12 小时前
深入解析 Rust + LLM 开发:手把手教你写一个 AI 运维助手
运维·人工智能·rust