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

相关推荐
Source.Liu4 小时前
【Chrono库】NaiveTime - Serde 序列化实现(naive/time/serde.rs)
rust·time
songroom8 小时前
Rust: 量化策略回测与简易线程池构建(MPMC)
开发语言·后端·rust
非专业程序员14 小时前
精读 GitHub - servo 浏览器(一)
前端·ios·rust
h***066515 小时前
项目升级Sass版本或升级Element Plus版本遇到的问题
前端·rust·sass
星释1 天前
Rust 练习册 72:多米诺骨牌与回溯算法
开发语言·算法·rust
百锦再2 天前
第21章 构建命令行工具
android·java·图像处理·python·计算机视觉·rust·django
星释2 天前
Rust 练习册 66:密码方块与文本加密
java·前端·rust
星释2 天前
Rust 练习册 57:阿特巴什密码与字符映射技术
服务器·算法·rust
星释2 天前
Rust 练习册 44:Trait 中的同名函数调用
开发语言·后端·rust
朝九晚五ฺ2 天前
深入Rust标准库(std):核心能力与实战指南
开发语言·后端·rust