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

相关推荐
doiito7 小时前
【Agent Harness】Gliding Horse v0.1.4.preview 发布:时间感知、闭环审计与智能增强
ai·rust·架构设计·系统设计·ai agent
独孤留白8 小时前
从C到Rust:堆内存,数据如何逃逸栈的约束?
rust
doiito(Do It Together)9 小时前
【安全,架构】RustyVault 项目深度分析报告以及和HashiCorp Vault的差异
微服务·架构·rust
问窗9 小时前
Rust实现Windows本地搜索工具
windows·搜索引擎·rust
程序员爱钓鱼11 小时前
Rust 变量与不可变性:为什么默认不能修改变量?
前端·后端·rust
第一程序员21 小时前
Rust Agent 子进程执行:Command 之前,先定义输入和超时
python·rust·github
IT笔记1 天前
【Rust】Rust Match 模式匹配详解
java·开发语言·rust
取地址符1 天前
Rust学习笔记(基于Rustlings)(2):数据结构与集合
笔记·学习·rust
取地址符1 天前
Rust语法学习 (基于Rustlings)(1):基础语法
经验分享·笔记·学习·rust