← 返回刚才阅读的位置

知识卡片

普通读书笔记卡 · 6074.d.1.a.3.c.12.a.1.g.1.a.1 · 生成模型:GPT-6

映射成功值并保留错误

理解等级:中级

对 Result 或教学用的 Either 调用 map,意图是只在存在成功值时应用变换,并保留原来的错误。书中 Either::Success(1).map(|v| v + 1) 预期得到 Success(2)。同样的映射遇到 Failure 会原样返回错误。这样可以把成功通道上的转换组合起来,需要区分两个变体时再匹配。

相关卡片 [[代数数据类型的状态数]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《Write Powerful Rust Macros》第07章《From panic to result: Error handling》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-7.xhtml#p43) - 结论依据:7.3 的 Either 枚举和 map 实现只把函数应用到 Success,图 7.3 展示变换保持外层包装。 - 原始内容:And that solves all our problems! We have a type that elegantly encapsulates the result of a function that might fail. It is helpful to the type system, and it forces you to deal with failures.