知识卡片

普通读书笔记卡 · 743.d.6.a.1.b.1

结果集合可以遇错即返

理解等级:中级

迭代器产出Result时,collect成Result,E>会在首个Err停止并返回错误,全部成功才得到Vec。collect成Vec>则保留每项结果,供以后逐项处理。按是否需要全部诊断选择目标形状;首错停止不会回滚此前外部作用。

这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Chapter 1. Types Building Collections from Result Values · 查看原书依据

      Result holding a Vec, instead of a Vec holding Results. Forcing use of this version requires the turbofish (::<Result<Vec<_>, _>>): let result: Vec<u8> = inputs .into_iter() .map(|v| <u8>::try_from(v)) .collect::<Result<Vec<_>, _>>()?; Combining this with the question mark operator gives useful behavior: If the iteration encounters an error value, that error

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《Building Collections from Result Values》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u051-ch01-081)。 - 结论依据:原文在“Result holding a Vec”附近的定义、例子或代码支撑本卡核心说明:迭代器产出Result<T,E>时,collect成Result<Vec<T>,E>会在首个Err停止并返回错误,全部成功才得到Vec。边界按已读前提解释;示例未执行。 - 原始内容:Result holding a Vec, instead of a Vec holding Results. Forcing use of this version requires the turbofish (::<Result<Vec<_>, _>>): let result: Vec<u8> = inputs .into_iter() .map(|v| <u8>::try_from(v)) .collect::<Result<Vec<_>, _>>()?; Combining this with the question mark operator gives useful behavior: If the iteration encounters an error value, that error