知识卡片
循环改写先保持行为再组合
改写循环时,先把索引访问换成直接迭代,再逐步提取筛选、数量限制、逐项变换和聚合。每一步检查选中的是同一批元素、处理顺序相同、何时停止一致。分步改写比一次压成复杂链更容易发现语义变化;明确性不足时可保留部分循环体。
这张卡片看不懂?
这张卡片的反馈已满 10 条,暂时无法继续提交。
已有反馈 · 0 / 10 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 1. Types Loop Transformation · 查看原书依据
The first step is to replace vector indexing with direct use of an iterator in a for-each loop: let mut even_sum_squares = 0; let mut even_count = 0; for value in values.iter() { if value % 2 != 0 { continue; } even_sum_squares += value * value; even_count += 1; if even_count == 5 { break; } } An initial arm of the loop that uses continue to skip over some i
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《Loop Transformation》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u052-ch01-082)。
- 结论依据:原文在“The first step”附近的定义、例子或代码支撑本卡核心说明:改写循环时,先把索引访问换成直接迭代,再逐步提取筛选、数量限制、逐项变换和聚合。边界按已读前提解释;示例未执行。
- 原始内容:The first step is to replace vector indexing with direct use of an iterator in a for-each loop: let mut even_sum_squares = 0; let mut even_count = 0; for value in values.iter() { if value % 2 != 0 { continue; } even_sum_squares += value * value; even_count += 1; if even_count == 5 { break; } } An initial arm of the loop that uses continue to skip over some i