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

相关推荐
程序员爱钓鱼12 小时前
Rust String 与 &str 详解:字符串所有权、借用与转换
前端·后端·rust
段一凡-华北理工大学1 天前
向量数据库实战:选型、调优与落地~系列文章12:文本分块策略实战:chunk_size 怎么选?重叠多少?
开发语言·数据库·后端·oracle·rust·工业智能体·高炉智能化
大卫小东(Sheldon)1 天前
小鹤音形词典:一个用 Rust 写的离线编码查询桌面工具
ai·rust
就业发动机1 天前
我用 Tauri 做了一个约 1.5 MB 的开源屏幕标注工具:MarkerOn
vue.js·rust
2601_954526751 天前
【硬核架构】打破 IT 与 OT 的数据孤岛!基于 Rust 异步协程的工业 IoT 网关重构,兼谈顶级自动化智能仪表厂家选型指南
物联网·架构·rust
white_ant1 天前
17- 文本统计/处理工具使用指南
rust·个人开发·tauri
独孤留白1 天前
Rust 类型转换全景指南 —— 从引用转换到序列化
rust
独孤留白1 天前
从C到Rust:Trait TryFrom TryInto 可能失败的类型转换
rust
雨师@1 天前
python通过rust编写组件扩展自己的能力
python·rust
程序员爱钓鱼2 天前
Rust 切片 Slice 详解:安全访问连续数据
前端·后端·rust