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

相关推荐
百锦再14 小时前
第21章 构建命令行工具
android·java·图像处理·python·计算机视觉·rust·django
星释16 小时前
Rust 练习册 66:密码方块与文本加密
java·前端·rust
星释1 天前
Rust 练习册 57:阿特巴什密码与字符映射技术
服务器·算法·rust
星释1 天前
Rust 练习册 44:Trait 中的同名函数调用
开发语言·后端·rust
朝九晚五ฺ1 天前
深入Rust标准库(std):核心能力与实战指南
开发语言·后端·rust
2013编程爱好者1 天前
Rust变量
开发语言·后端·rust
yezipi耶不耶1 天前
Cloudflare 11.18 故障深度复盘:当“极致优化”撞上“现实边界“
rust·web
星释1 天前
Rust 练习册 60:鲍勃与字符串处理的状态机思维
开发语言·网络·rust
s9123601011 天前
【Openwrt】M4 Macmini编译Openwrt的Dockerfile
rust
星释1 天前
Rust 练习册 21:Hello World 与入门基础
开发语言·后端·rust