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

相关推荐
爱编程的小庄16 分钟前
Rust初识
开发语言·rust
爱编程的小庄2 小时前
Rust 发行版本及工具介绍
开发语言·后端·rust
skywalk81634 小时前
FreeBSD下安装rustup、cargo和uv
开发语言·python·rust·cargo
咸甜适中5 小时前
双色球、大乐透兑奖分析小程序(rust_Tauri + Vue3 + sqlite)
爬虫·rust·sqlite·vue3·tauri2
rustfs6 小时前
使用 podman 容器化安装 RustFS 详细指南
docker·rust·podman
FAFU_kyp1 天前
Rust 泛型(Generics)学习教程
开发语言·学习·rust
木木木一2 天前
Rust学习记录--C12 实例:写一个命令行程序
学习·算法·rust
柠檬丶抒情2 天前
Rust深度学习框架Burn 0.20是否能超过python?
python·深度学习·rust·vllm
Vallelonga2 天前
浅谈 Rust bindgen 工具
开发语言·rust
木木木一2 天前
Rust学习记录--C13 Part1 闭包和迭代器
开发语言·学习·rust