Rust cơ bản

Rust Loops: for, while and loop

Three ways to repeat code in Rust, and how break can return a value from loop.

  • Cơ bản
  • Đọc trong 3 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • for over a range
  • while with a condition
  • loop with break
for n in 1..=3
1print
2print
3print
4not in range
The range 1..=3 produces 1, 2 and 3.

Three loops for three jobs

Rust has three loops. for visits each item of a range or collection, while repeats as long as a condition is true, and loop repeats until you break out of it.

1..=3 is a range that includes 3; 1..3 would stop at 2. The while loop ends when countdown reaches 0. break total leaves the loop and returns a value, which is stored in result.

Những điểm quan trọng

  1. 1..=3 includes 3; 1..3 stops at 2.
  2. while repeats as long as the condition is true.
  3. break value leaves loop and returns the value.

Ví dụ Rust chạy được

Rust
Chạy code →
main.rs
fn main() {
    for n in 1..=3 {
        println!("for: {n}");
    }

    let mut countdown = 3;
    while countdown > 0 {
        println!("while: {countdown}");
        countdown -= 1;
    }

    let mut total = 0;
    let result = loop {
        total += 10;
        if total >= 30 {
            break total;
        }
    };
    println!("loop result: {result}");
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
for: 1
for: 2
for: 3
while: 3
while: 2
while: 1
loop result: 30

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Tiếp theo: Prime Numbers →

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách