Infinite Loop
Part of the Fundamentals section of Coddy's Rust journey — lesson 43 of 75.
In Rust, infinite loops can be created using either loop or while true. Both run until explicitly stopped with break or program termination.
For example:
loop {
// Code to be executed repeatedly
if condition {
break; // Exit the loop if the condition is met
}
}The loop continues until it reaches a break. It's useful for programs that need to run continuously, like servers or devices.
Here's an example of an infinite loop that prints numbers until a specific condition is met:
let mut count = 0;
loop {
println!("Count: {}", count);
count += 1;
if count > 5 {
break;
// Exit the loop when count is greater than 5
}
}In this example, the loop will print numbers from 0 to 5 and then exit when count becomes 6.
Challenge
BeginnerWrite a Rust program that simulates a simple counter. The program should use an infinite loop to continuously increment a counter and print its value. The loop should terminate when the counter reaches a specific value determined by the input.
Steps for the program:
- Initialize a mutable variable
counterto 0. - Use an infinite loop (
loop) to continuously increment thecounterby 1 in each iteration. - Inside the loop, print the current value of
counter. - Check if
counteris equal to the user-provided termination value. If it is, break out of the loop.
Cheat sheet
Infinite loops in Rust can be created using loop or while true. They run until explicitly stopped with break.
Basic infinite loop syntax:
loop {
// Code to be executed repeatedly
if condition {
break; // Exit the loop if the condition is met
}
}Example with counter:
let mut count = 0;
loop {
println!("Count: {}", count);
count += 1;
if count > 5 {
break;
}
}Try it yourself
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let limit: i32 = input.trim().parse().unwrap();
let mut counter = 0;
// Write your code below
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input