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

相关推荐
怪我冷i2 小时前
解决win11运行cargo run的报错,Blocking waiting for file lock on build directory
rust·web·zed·salvo
大卫小东(Sheldon)5 小时前
Rudist 0.4.3 发布:让 AI Agent 替你操作 Redis
ai·rust·rudist
Source.Liu6 小时前
【zip-rs】zip 压缩库选型分析:通用性 vs Rust 支持力度
rust·zip-rs
美利坚国王6 小时前
多代理协作拆成“真实进程、真实消息、真实段落、真实绑定关系”的运行时系统
rust
Rust研习社7 小时前
手把手带你写 Rust 测试
rust
会飞的不留神8 小时前
【手搓编译器】局部变量存储
rust·编译器·解释器·lox
怪我冷i9 小时前
在win11进行Rust Web 开发,采用Salvo框架
开发语言·前端·rust
司马万9 小时前
RUST基础1----数据类型
开发语言·算法·rust
十里平湖满秋霜1 天前
RUST基础语法--数据类型
rust
Amos_Web1 天前
Rspack 源码解析 (1) —— 架构总览:从 Node.js 到 Rust 的跨界之旅
前端·rust·node.js