4.4.1 `for` 循环

01-for 循环 — Comprehensive Rust

译文 · 基于 Comprehensive Rust

原文链接: https://google.github.io/comprehensive-rust/control-flow-basics/loops/for.html

4.4.1 for 循环

for 循环 会遍历值的范围或集合中的元素:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Copyright 2024 Google LLC
// SPDX-License-Identifier: Apache-2.0
fn main() {
    for x in 1..5 {
        dbg!(x);
    }

    for elem in [2, 4, 8, 16, 32] {
        dbg!(elem);
    }
}
  • 底层上,for 循环使用称为“迭代器”(iterator)的概念来处理对不同范围/集合的遍历。迭代器稍后会更详细讨论。
  • 注意第一个 for 循环只迭代到 4。演示 1..=5 语法表示闭区间范围。
最后修改 August 11, 2026: 更新 (70a5af133)