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

相关推荐
Dreamfine5 小时前
Rust将结构导出到json如何处理小数点问题
rust·json·dolphindb·rust_decimal·serde_json
muyouking1114 小时前
Rust多线程性能优化:打破Arc+锁的瓶颈,效率提升10倍
开发语言·性能优化·rust
heroboyluck1 天前
rust 全栈应用框架dioxus
前端·rust·dioxus
华纳云IDC服务商2 天前
如何利用Rust提升Linux服务器效率(详细操作指南)
linux·服务器·rust
UestcXiye2 天前
Rust 学习笔记:结构体(struct)
rust
若愚67922 天前
Tauri 跨平台开发指南及实战:用前端技术征服桌面应用(合集-万字长文)
前端·vue.js·rust·gitcode
夕水2 天前
自动化按需导入组件库的工具rust版本完成开源了
前端·rust·trae
s9123601012 天前
Rust Ubuntu下编译生成环境win程序踩坑指南
windows·ubuntu·rust
s9123601012 天前
Rust std::thread::spawn(move) 的作用
开发语言·后端·rust
苏近之3 天前
深入理解 Rust 中的生命周期
rust