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

相关推荐
花间相见9 小时前
【终端效率工具01】—— Yazi:Rust 编写的现代化终端文件管理器,告别繁琐操作
前端·ide·git·rust·极限编程
fox_lht10 小时前
7.3.结构体-方法
开发语言·后端·rust
Tomhex11 小时前
Rust生命周期标注核心原理
rust
代码羊羊11 小时前
Rust基础类型与变量全解析
开发语言·后端·rust
Tomhex12 小时前
Rust交叉编译用rust-lld配置指南
rust
朝阳58114 小时前
MAVLink 消息处理指南
rust·mavlink
小杍随笔16 小时前
【Rust 1.95.0 正式发布!语言特性、标准库、平台支持全面升级,一文带你看完整更新】
开发语言·rust·策略模式
浪客川16 小时前
【百例RUST - 008】枚举
开发语言·后端·rust
techdashen17 小时前
Rust 在安全关键软件:机遇、挑战与未来之路
人工智能·安全·rust