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

相关推荐
l1t8 小时前
测试DuckDB电子表格读取插件rusty_sheet 0.2版
数据库·rust·插件·xlsx·duckdb
嚴寒18 小时前
被10个终端窗口逼疯后,我用Rust写了个零依赖跨平台终端Agent启动神器
rust·agent
alwaysrun2 天前
Rust中模式匹配
rust·match·模式匹配·if let·while let·值绑定
编码浪子2 天前
Dioxus hot-dog 总结
rust
光影少年3 天前
rust生态及学习路线,应用领域
开发语言·学习·rust
Kiri霧3 天前
Linux下的Rust 与 C 的互操作性解析
c语言·开发语言·rust
大鱼七成饱3 天前
Rust 多线程编程入门:从 thread::spawn 步入 Rust 并发世界
后端·rust
ServBay4 天前
Rust 1.89更新,有哪些值得关注的新功能
后端·rust
MOON404☾5 天前
Rust程序语言设计(5-8)
开发语言·后端·rust
Vallelonga5 天前
Rust 中的数组和数组切片引用
开发语言·rust