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

相关推荐
唐装鼠1 分钟前
rust自动调用Deref(deepseek)
开发语言·算法·rust
jump_jump21 分钟前
手写一个 Askama 模板压缩工具
前端·性能优化·rust
行走的陀螺仪3 小时前
Sass 详细指南
前端·css·rust·sass
七月丶5 小时前
实战复盘:我为什么把 TypeScript 写的 CLI 工具用 Rust 重写了一遍?
前端·后端·rust
Source.Liu9 小时前
【Rust】字符类型详解
rust
周小码9 小时前
Spacedrive:用Rust构建的虚拟分布式文件系统
开发语言·后端·rust
Source.Liu10 小时前
【Rust】浮点数详解
rust
Bigger11 小时前
Tauri (23)——为什么每台电脑位置显示效果不一致?
前端·rust·app
框架主义者13 小时前
N2N Maid - 一个开源多端的 N2N 图形界面
计算机网络·rust
Source.Liu13 小时前
【Rust】范围 Range详解
rust