知识卡片
收集结果决定首错返回
在 Rust 中,如果迭代器产生 Result<Stmt, syn::Error>,可用目标类型 Result<Vec<Stmt>, syn::Error> 调用 collect()。全部项成功时,结果携带语句向量;遇到首个错误就停止并返回该错误。调用方随后可用 ? 传播。此写法适用于任何一个失败就使整体结果无效的转换。想继续扫描并保留多个诊断时,需要采用不同的遍历和累积方式。
相关卡片 [[组合独立的编译诊断]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
- · 传播或组合诊断
原书出处 · 1 处
- From panic to result: Error handling 传播或组合诊断 · 查看原书依据
Another cool Rust feature makes its appearance in the previous code. As you can see, we map over statements and return a Result for each one. That means our output should be Vec<Result<Stmt, syn::Error>>. But the output type I defined for new_statements in handle_expression is Result<Vec<Stmt>, syn::Error>! In the functional world, this is called traverse, which allows stacking your enums (actually, monads, but let’s not get into that) in different ways.
参考来源
- 位置:《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#p151)
- 结论依据:7.9.1 解释 FromIterator 如何收集 Result,并指出 Result<Vec<_>, _> 只能保留一个错误。
- 原始内容:Another cool Rust feature makes its appearance in the previous code. As you can see, we map over statements and return a Result for each one. That means our output should be Vec<Result<Stmt, syn::Error>>. But the output type I defined for new_statements in handle_expression is Result<Vec<Stmt>, syn::Error>! In the functional world, this is called traverse, which allows stacking your enums (actually, monads, but let’s not get into that) in different ways.