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

相关推荐
集成显卡3 小时前
Rust实战七 |基于带 colored 颜色文字控制台的批量文件删除工具
开发语言·后端·rust
零点一顿微胖11 小时前
[Agent]实现获取系统基本信息接口 Rust版
开发语言·rust
小宇子2B12 小时前
Copy 明明比 Clone 便宜,为什么 Rust 偏偏要求你「先实现 Clone」?
rust
小宇子2B13 小时前
一个 Vec 在内存里到底长什么样:从真实地址看 move 为什么不要钱
rust
特立独行的猫a17 小时前
鸿蒙 PC 移植记:将微软的 `edit` 轻量级终端编辑器带到 OpenHarmony
microsoft·rust·编辑器·harmonyos·鸿蒙pc·edit
@小匠17 小时前
WebDAV 同步踩坑实录:从 405 到数据恢复不生效的完整排查
rust
爱学习的鱼佬19 小时前
告别内网模型接入烦恼!ModelStandardization:让 Open WebUI等工具无缝对接私有大模型
rust·开源·大模型·openai·openwebui·model api代理·内网部署
Rust研习社1 天前
90% 的 Rust 新手都不知道的 3 个实用开发技巧
后端·rust·编程语言
析数塔2 天前
编译两分钟,修改五秒钟:Zig构建系统重构解决的老问题
程序员·rust
Kapaseker2 天前
Rust 是如何干掉空指针的
rust·kotlin