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

相关推荐
小杍随笔3 小时前
【Rust 语言编程知识与应用:自定义数据类型详解】
开发语言·后端·rust
咚为5 小时前
Rust 跨平台编译实战:从手动配置到 Cross 容器化
开发语言·后端·rust
幸福指北8 小时前
我用 Tauri + Vue 3 + Rust 开发了一款跨平台网络连接监控工具Portview,性能炸裂!
前端·网络·vue.js·tcp/ip·rust
咚为8 小时前
深入浅出 Rust FFI:从内存安全到二进制兼容
开发语言·安全·rust
a11177610 小时前
剪切板助手TieZ(开源项目rust)
rust·开源·剪切板
盒马盒马1 天前
Rust:迭代器
开发语言·后端·rust
Source.Liu1 天前
【Iced】stream.rs文件
rust·iced
Kapaseker1 天前
精通 Rust 宏 — 包装新类型
rust
飞函安全1 天前
Vite 8.0:Rust.bundle,性能提升10-30倍
开发语言·人工智能·rust
奋斗中的小猩猩2 天前
OpenClaw不安全,Rust写的ZeroClaw给出满意答案
安全·rust·openclaw·小龙虾