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

相关推荐
奋斗中的小猩猩1 小时前
OpenClaw不安全,Rust写的ZeroClaw给出满意答案
安全·rust·openclaw·小龙虾
海奥华21 小时前
Rust初步学习
开发语言·学习·rust
VermouthSp4 小时前
上下文切换
linux·rust
小杍随笔11 小时前
【Rust 1.94.0 正式发布:数组窗口、Cargo 配置模块化、TOML 1.1 全面升级|开发者必看】
开发语言·后端·rust
敬业小码哥1 天前
记一次:clion使用rust插件配置环境并开发
学习·rust
NGINX开源社区1 天前
NGINX 引入对 ACME 协议的原生支持
nginx·rust
Rust语言中文社区1 天前
【Rust日报】 CEL与Rust实现接近原生速度的解释执行
开发语言·后端·rust
FreeBuf_2 天前
恶意Rust组件与AI机器人利用CI/CD管道窃取开发者密钥
人工智能·ci/cd·rust
水月wwww2 天前
Rust的安装与卸载 | windows
开发语言·windows·rust
Mem0rin2 天前
[自用]Rust速通day5:包、crate和use
rust