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

相关推荐
敬业小码哥3 小时前
记一次:clion使用rust插件配置环境并开发
学习·rust
NGINX开源社区6 小时前
NGINX 引入对 ACME 协议的原生支持
nginx·rust
Rust语言中文社区7 小时前
【Rust日报】 CEL与Rust实现接近原生速度的解释执行
开发语言·后端·rust
FreeBuf_9 小时前
恶意Rust组件与AI机器人利用CI/CD管道窃取开发者密钥
人工智能·ci/cd·rust
水月wwww21 小时前
Rust的安装与卸载 | windows
开发语言·windows·rust
Mem0rin1 天前
[自用]Rust速通day5:包、crate和use
rust
Ivanqhz1 天前
活跃范围重写(Live Range Rewriting)
开发语言·c++·后端·算法·rust
Roc.Chang1 天前
Rust 入门 - RustRover 新建项目时四种项目模板对比
开发语言·后端·rust
勇敢牛牛_2 天前
【conreg-client】在Rust中使用向Feign一样的远程调用
网络·rust·feign
小杍随笔2 天前
【Rust模块化进阶:深入解析mod.rs的用法与现代实践(1.94版本)】
开发语言·后端·rust