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

相关推荐
维维酱13 小时前
Rust - 互斥锁
rust
维维酱14 小时前
Rust - 共享状态的并发
rust
ArcX16 小时前
从 JS 到 Rust 的旅程
前端·javascript·rust
Humbunklung16 小时前
Rust Floem UI 框架使用简介
开发语言·ui·rust
寻月隐君20 小时前
深入解析 Rust 的面向对象编程:特性、实现与设计模式
后端·rust·github
KENYCHEN奉孝2 天前
基于 actix-web 框架的简单 demo
前端·rust
love530love2 天前
【笔记】旧版MSYS2 环境中 Rust 升级问题及解决过程
开发语言·人工智能·windows·笔记·python·rust·virtualenv
Humbunklung2 天前
Rust 函数
开发语言·后端·rust
荣江2 天前
【实战】基于 Tauri 和 Rust 实现基于无头浏览器的高可用网页抓取
后端·rust
susnm2 天前
创建你的第一个 Dioxus app
rust·全栈