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

相关推荐
shimly1234561 小时前
(done) 速通 rustlings(11) 向量vector及其操作
rust
shimly1234561 小时前
(done) 速通 rustlings(3) intro1 println!()
rust
shimly1234561 小时前
(done) 速通 rustlings(12) 所有权
rust
shimly1234563 小时前
(done) 速通 rustlings(7) 全局变量/常量
rust
敲敲了个代码3 小时前
构建工具的第三次革命:从 Rollup 到 Rust Bundler,我是如何设计 robuild 的
开发语言·前端·javascript·后端·rust
lpfasd1233 小时前
Tauri 中实现自更新(Auto Update)
rust·tauri·update
shimly1234563 小时前
(done) 速通 rustlings(10) 基本数据类型
rust
shimly1234563 小时前
(done) 速通 rustlings(8) 函数
rust
busideyang3 小时前
MATLAB vs Rust在嵌入式领域的角色定位
开发语言·matlab·rust
Source.Liu5 小时前
【a11】项目命名笔记:`a11` (合一)
rust·egui