Exploring Rust Infinite Loops

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we explore the usage of the loop keyword in Rust, which allows us to create an infinite loop. We can exit the loop at any time using the break statement and skip the remaining iterations using the continue statement. The provided example code demonstrates how to increment a counter and print its value until it reaches a certain condition, utilizing continue to skip one iteration and break to exit the loop entirely.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/BasicConceptsGroup(["`Basic Concepts`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/MemorySafetyandManagementGroup(["`Memory Safety and Management`"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/BasicConceptsGroup -.-> rust/mutable_variables("`Mutable Variables`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/MemorySafetyandManagementGroup -.-> rust/lifetime_specifiers("`Lifetime Specifiers`") subgraph Lab Skills rust/variable_declarations -.-> lab-99304{{"`Exploring Rust Infinite Loops`"}} rust/mutable_variables -.-> lab-99304{{"`Exploring Rust Infinite Loops`"}} rust/function_syntax -.-> lab-99304{{"`Exploring Rust Infinite Loops`"}} rust/expressions_statements -.-> lab-99304{{"`Exploring Rust Infinite Loops`"}} rust/lifetime_specifiers -.-> lab-99304{{"`Exploring Rust Infinite Loops`"}} end

loop

Rust provides a loop keyword to indicate an infinite loop.

The break statement can be used to exit a loop at anytime, whereas the continue statement can be used to skip the rest of the iteration and start a new one.

fn main() {
    let mut count = 0u32;

    println!("Let's count until infinity!");

    // Infinite loop
    loop {
        count += 1;

        if count == 3 {
            println!("three");

            // Skip the rest of this iteration
            continue;
        }

        println!("{}", count);

        if count == 5 {
            println!("OK, that's enough");

            // Exit this loop
            break;
        }
    }
}

Summary

Congratulations! You have completed the Loop lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like