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

相关推荐
明天好,会的33 分钟前
分形生成实验(三):Rust强类型驱动的后端分步实现与编译时契约
开发语言·人工智能·后端·rust
superman超哥1 小时前
Rust API 设计的零成本抽象原则:性能与表达力的完美统一
开发语言·后端·rust·rust api·抽象原则·性能与表达力
superman超哥1 小时前
Rust 所有权的三大基本规则:内存安全的类型系统基石
开发语言·后端·rust·内存安全·rust所有权·基本规则·系统基石
superman超哥1 小时前
Rust 线程安全性保证(Send 与 Sync):编译期并发安全的类型系统
开发语言·后端·rust·编程语言·并发安全·send与sync·rust线程
问道飞鱼17 小时前
【Rust编程】Cargo 工具详解:从基础到高级的完整指南
开发语言·后端·rust·cargo
古城小栈17 小时前
rust 中的 结构体 & 枚举
开发语言·rust
C++chaofan18 小时前
JUC 中 synchronized 的底层实现原理解析——Monitor
java·开发语言·c++·rust·ruby·juc·字节码
拾荒李20 小时前
使用Webassembly实现图片压缩
前端·javascript·性能优化·rust·wasm·webassembly
古城小栈1 天前
rust中的两大枚举:Option 和 Result
开发语言·rust
许泽宇的技术分享1 天前
打破AI调用壁垒:Antigravity Tools如何用Rust+Tauri重构你的AI工作流
人工智能·重构·rust