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

相关推荐
xiyijixiyifula34 分钟前
用 Rust 构建公司部门管理系统:HashMap 与 Vec 的实践应用
rust
AI智动派1 天前
从 Python 到 Rust:深入解析 LLM Agent 工具调用的内存安全与异步并发重构实践
rust
_朱志鹏1 天前
Rust练手项目1--minigrep
rust
ssshooter2 天前
Tauri 项目实践:客户端与 Web 端的授权登录实现方案
前端·后端·rust
AI智动派2 天前
《深入 Rust Async/Await:如何实现一个带超时保护与安全沙箱的 LLM Agent 循环》
rust
范特西林4 天前
一次 to_bits() 引发的 Rust 与 C++ 底层思考
rust
冬奇Lab5 天前
一天一个开源项目(第42篇):OpenFang - 用 Rust 构建的 Agent 操作系统,16 层安全与 7 个自主 Hands
人工智能·rust·开源
量子位5 天前
Transformer论文作者重造龙虾,Rust搓出钢铁版,告别OpenClaw裸奔漏洞
rust·openai·ai编程
哈里谢顿5 天前
Rust 语言入门博客
rust
DongLi017 天前
rustlings 学习笔记 -- exercises/06_move_semantics
rust