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

相关推荐
古城小栈4 小时前
从 cargo-whero 库中,找到提升 rust 的契机
开发语言·后端·rust
techdashen9 小时前
Cloudflare 为何抛弃 NGINX,用 Rust 自研了一个代理
运维·nginx·rust
Mr.Rice.Fool12 小时前
rust面试经验1
后端·面试·职场和发展·rust
本地化文档13 小时前
rust-nomicon-l10n
rust·github·gitcode
代码羊羊13 小时前
Rust 格式化输出完全攻略:从入门到精通
开发语言·后端·rust
Rust研习社13 小时前
Rust + PostgreSQL 极简技术栈应用开发
开发语言·数据库·后端·http·postgresql·rust
古城小栈15 小时前
rust 亿级并发模型,实践完成
开发语言·网络·rust
qcx2315 小时前
Warp源码深度解析(一):GPU加速+AI Agent的下一代终端架构全景
人工智能·架构·rust
暮色念了红尘16 小时前
CC Switch — Ubuntu 20.04 可用版本
ubuntu·ai·rust·ubuntu 20.04·vibe coding·cc swich