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

相关推荐
爱分享的阿Q3 小时前
Rust加WebAssembly前端性能革命实践指南
前端·rust·wasm
沉淀粉条形变量10 小时前
rust 单例模式
开发语言·单例模式·rust
skilllite作者11 小时前
SkillLite 多入口架构实战:CLI / Python SDK / MCP / Desktop / Swarm 一页理清
开发语言·人工智能·python·安全·架构·rust·agentskills
Rust研习社12 小时前
深入理解 Rust 闭包:从基础语法到实战应用
rust
Rust研习社12 小时前
Rust 时间处理神器:chrono 从入门到实战
rust
Rust研习社12 小时前
Rust 异步 ORM 新选择:Toasty 初探
rust
星辰徐哥13 小时前
异步定时任务系统的设计与Rust实战集成
开发语言·后端·rust
swear0113 小时前
【VSCODE 插件 rust-analyzer 使用】打开文件夹
ide·vscode·rust
laomocoder14 小时前
AI网关设计
人工智能·rust·系统架构
zandy101115 小时前
业界首发|衡石科技HENGSHI CLI重磅登场,以Rust架构开启Agentic BI自动驾驶时代
科技·架构·rust·agentic bi