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

相关推荐
xjz184212 小时前
Rust 用 `&&`、`||`、`!` 把条件组合起来
rust
不积跬步无以至千里mmbb2617 小时前
Rust三大核心:Trait Crate Mod详解
linux·rust
SomeOtherTime21 小时前
第 2 讲:借用检查器(Borrow Checker)的数学本质——读写锁的编译期化、非词法生命周期(NLL)与重借用(Reborrowing)
rust
xjz18422 天前
Rust 的else:把「做不做」升级成「二选一」
rust
喵个咪2 天前
RushWind Admin — update_mask 写面:字段级白名单、显式清除与点路径合并
后端·rust
喵个咪2 天前
RushWind Admin — 多租户行级隔离与租户回收站:Viewer 三态、repo_shell! 与全域级联清除
后端·rust
喵个咪2 天前
RushWind CMS — 三服务拓扑:core 领域层、双 BFF 薄代理与一份契约的双面输出
后端·rust
不积跬步无以至千里mmbb262 天前
Rust内核开发核心入口解析
linux·rust
wflynn3 天前
GitHub 今日推荐|rust-anything:录制真实输入输出,渐进式重写热点函数到 Rust
rust·开源·github·cli·claude-code·agent-skills
风笙9784 天前
[Rust] String 与 &str 详解
rust