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

相关推荐
花褪残红青杏小19 小时前
Rust图像处理第17节-Julia 朱利亚分形:拖动常数 c 看图实时变化
rust·webassembly·图形学
An_s1 天前
rust开发wasm与浏览器(js)交互
javascript·rust·wasm
Mr -老鬼1 天前
Zed WASM扩展开发全套踩坑记录(WASI适配、LSP插件开发避坑指南)
rust·wasm·lsp·zed·ai ide·语言服务器
糯米导航1 天前
Rust + ONNX Runtime 构建生产级 AI 推理服务:从零到压测
开发语言·人工智能·rust
Arman37681 天前
rusty-cat 分片并发上传完全指南
rust·vibecoding
独孤留白1 天前
从C到Rust:mut 可变性,与恶魔战斗的利剑
rust
Rockbean1 天前
10分钟-AI × Solana:2.MCP服务器——AI代理接入Solana的标准化通道
rust·web3·智能合约
一次旅行2 天前
【AI工具】Rust-Based CLI:用 xargs 和并行加速你的 Linux 日常
linux·开发语言·rust
梦醒沉醉2 天前
6、Rust程序设计语言——包、crates与模块
rust
花褪残红青杏小2 天前
Rust图像处理第16节-曼德博集合 Mandelbrot:用一行公式画出无限细节
rust·webassembly·图形学