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

相关推荐
Zenova EdgeOS1 小时前
Rust 数据库实战:工业边缘场景下的 sqlx
数据库·oracle·rust·边缘计算·工业网关
用户460438522508618 小时前
关于paimon- rust的学习 --- Table(一)
大数据·rust
Kapaseker21 小时前
快 18 倍?Laravel Rust 才是 Laravel 的未来
rust
Edgarye1 天前
Rust + Vue 3 前后端开发框架 RyFrame:从参数更新到操作审计
rust
loulanyue_1 天前
AI智能体24小时复刻Photoshop:什么该交给Agent、什么必须留给人——读Brandon Thomas演讲实录
人工智能·ui·rust·ai编程·photoshop
wasabihu2 天前
为什么别给 AI 浏览器 MCP 开全盘文件上传:原生 CDP 零拷贝与 4 道 Fail-Closed 防线
rust
孟陬3 天前
Foobar 技术周刊#2:约会已死?用户急剧下滑,约会App大概率会弱化约会属性转向轻陪伴。我有个建议:
前端·后端·rust
不积跬步无以至千里mmbb263 天前
【软件工艺师 rust相关课程】
开发语言·后端·rust
穗余3 天前
以太坊面试深度:transfer vs send vs call.value 机制与 2300 Gas 限制
rust·solidity面试·eip-1884·eip-2929·returnbomb
Kapaseker3 天前
百炼成金!Rust 1.100.0 正式发布
rust