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

相关推荐
rainchestnut14 小时前
bevy初体验2-官方示例学习
rust
葡萄城技术团队17 小时前
Hurley:用 Rust 打造的高性能 HTTP 客户端 + 压测工具
开发语言·http·rust
Source.Liu20 小时前
【dxf-rs】库全面介绍
rust·dxf-rs
土豆12501 天前
Rust宏编程完全指南:用元编程解锁Rust的终极力量
rust·编程语言
小杍随笔1 天前
【Rust 语言编程知识与应用:基础数据类型详解】
开发语言·后端·rust
小杍随笔2 天前
【Rust 语言编程知识与应用:自定义数据类型详解】
开发语言·后端·rust
咚为2 天前
Rust 跨平台编译实战:从手动配置到 Cross 容器化
开发语言·后端·rust
幸福指北2 天前
我用 Tauri + Vue 3 + Rust 开发了一款跨平台网络连接监控工具Portview,性能炸裂!
前端·网络·vue.js·tcp/ip·rust
咚为2 天前
深入浅出 Rust FFI:从内存安全到二进制兼容
开发语言·安全·rust
a1117762 天前
剪切板助手TieZ(开源项目rust)
rust·开源·剪切板