0
0
Rustprogramming~5 mins

Loop construct in Rust

Choose your learning style9 modes available
Introduction

Loops help you repeat actions many times without writing the same code again and again.

When you want to count from 1 to 10 and print each number.
When you need to keep asking a user for input until they give a valid answer.
When you want to process each item in a list one by one.
When you want to repeat a task until a certain condition is met.
Syntax
Rust
loop {
    // code to repeat
    if condition {
        break;
    }
}

loop creates an infinite loop unless you use break to stop it.

You can use break to exit the loop when needed.

Examples
This prints "Hello!" once and then stops the loop.
Rust
loop {
    println!("Hello!");
    break;
}
This counts from 1 to 5 and prints each number, then stops.
Rust
let mut count = 0;
loop {
    count += 1;
    println!("Count: {}", count);
    if count == 5 {
        break;
    }
}
Sample Program

This program prints numbers from 1 to 3 using a loop. It stops when the number is greater than 3.

Rust
fn main() {
    let mut number = 1;
    loop {
        println!("Number is {}", number);
        number += 1;
        if number > 3 {
            break;
        }
    }
}
OutputSuccess
Important Notes

Loops can run forever if you forget to use break. Always make sure your loop can stop.

You can use continue inside loops to skip to the next repetition.

Summary

Loops repeat code multiple times without rewriting it.

loop creates an infinite loop that you stop with break.

Use loops to handle repeated tasks easily and clearly.