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

相关推荐
FAFU_kyp3 小时前
Rust 的 引用与借用
开发语言·算法·rust
superman超哥4 小时前
路由的艺术:Rust Web 框架中的高效匹配与类型安全提取
开发语言·rust·编程语言·rust web框架·rust路由
木木木一7 小时前
Rust学习记录--C10 泛型,Trait,生命周期
python·学习·rust
Mr -老鬼7 小时前
Rust 知识图-谱基础部分
开发语言·后端·rust
盛者无名8 小时前
Rust语言基础
开发语言·后端·rust
FAFU_kyp9 小时前
Rust 所有权(Ownership)学习
开发语言·学习·rust
superman超哥9 小时前
Rust 异步性能的黑盒与透视:Tokio 监控与调优实战
开发语言·后端·rust·编程语言·rust异步性能·rust黑盒与透视·tokio监控与调优
Mr -老鬼9 小时前
Rust 知识图谱 -进阶部分
开发语言·后端·rust
古城小栈9 小时前
Cargo.toml
开发语言·后端·rust
古城小栈10 小时前
Cargo命令工具
开发语言·rust