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

相关推荐
沛沛rh451 小时前
Rust 中的三个“写手“:print!、format!、write! 的详细区别
开发语言·后端·rust
henreash1 小时前
Rust引用借用测试
rust
devmoon2 小时前
从 0 到 1 实现两条独立区块链Parachain的跨链通信能力之实操指南
开发语言·rust·区块链·信息与通信·polkadot
devmoon3 小时前
区块链 Indexer 全解析:为什么 Web3 应用离不开数据索引器?(Polkadot / Ethereum / Solana 对比与未来展望)
rust·web3·区块链·以太坊·polkadot·solana·indexer
@PHARAOH3 小时前
WHAT - SWC Rust-based platform for the Web
开发语言·前端·rust
大鹏的NLP博客5 小时前
Rust + PyTorch 实现 BGE 向量检索系统
人工智能·pytorch·rust
无名之逆21 小时前
你可能不需要WebSocket-服务器发送事件的简单力量
java·开发语言·前端·后端·计算机·rust·编程
Source.Liu1 天前
【egui】界面的坐标系统:f32 一统江湖
rust·egui
班公湖里洗过脚1 天前
Rust解析mp3文件及工作目录下多个项目维护示例
rust
sunny_2 天前
构建工具的第三次革命:从 Rollup 到 Rust Bundler,我是如何设计 robuild 的
前端·rust·前端工程化