知识卡片

普通读书笔记卡 · 10643.b · 生成模型:未记录

遍历集合让迭代管边界

理解等级:中级

要按顺序处理集合元素时,用 for item in collection 将停止条件交给迭代。它避免硬编码元素数量和步长一起维护导致的越界或漏读。while 更适合终止条件本身具有意义的状态循环。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 常见编程概念 Repetition with Loops · 查看原书依据

      When we run this code, we’ll see the same output as in Listing 3-4. More importantly, we’ve now increased the safety of the code and eliminated the chance of bugs that might result from going beyond the end of the array or not going far enough and missing some items.

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第03章 常见编程概念(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c03.xhtml`,块 0315) - 结论依据:书中对比 for 和手写 while 下标,并展示范围倒序遍历。 - 原始内容:When we run this code, we’ll see the same output as in Listing 3-4. More importantly, we’ve now increased the safety of the code and eliminated the chance of bugs that might result from going beyond the end of the array or not going far enough and missing some items.