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

相关推荐
ALex_zry3 小时前
C语言底层编程与Rust的现代演进:内存管理、系统调用与零成本抽象
c语言·算法·rust
ALex_zry3 小时前
内核开发者的视角:C与Rust在系统编程中的哲学与实践
c语言·开发语言·rust
u***45163 小时前
Windows安装Rust环境(详细教程)
开发语言·windows·rust
星释4 小时前
Rust 练习册 101:字符串序列切片的艺术
开发语言·后端·rust
Source.Liu5 小时前
【Chrono库】Android和OpenHarmony系统绑定(src/offset/local/tz_data.rs)
rust·time
S***q19215 小时前
Rust在系统工具中的内存安全给代码上了三道保险锁。但正是这种“编译期的严苛”,换来了运行时的安心。比如这段代码:
开发语言·后端·rust
T***u33316 小时前
Rust在Web中的 Web框架
开发语言·后端·rust
Q***f63517 小时前
Rust在嵌入式中的功耗优化
开发语言·后端·rust
H***997617 小时前
Rust包管理策略
开发语言·后端·rust
p***s9119 小时前
Windows安装Rust环境(详细教程)
开发语言·windows·rust