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

相关推荐
Kapaseker21 小时前
离开 Swift,转向 Rust
rust
钱栈up1 天前
GitHub 热榜实测|worktrunk 环境部署实录
rust·开源·github
喵个咪2 天前
RushWind Shop — 一笔订单的穿越:电商买路径上的每一道闸门
后端·微服务·rust
Kapaseker2 天前
5分钟学会 Rust 常见集合
rust
撸码猿3 天前
Ladybird 进入 alpha:从零写的浏览器引擎现在能下载了
c++·rust·开源·浏览器·ladybird
wflynn3 天前
GitHub 今日推荐|xcl:在 Windows PC 上直接运行 Xbox Series X|S 游戏
rust·开源·github·d3d12·gdk·rdna2
geovindu4 天前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
喵个咪4 天前
RushWind Admin — 模块化单体:一个进程与通往微服务的五级阶梯
后端·架构·rust
喵个咪4 天前
RushWind CMS — 最小微服务实例:微服务架构的最小完备集
后端·架构·rust
geovindu5 天前
rust: Timing Functions Pattern
开发语言·后端·设计模式·rust·计时函数模式·性能分析型模式