While Loop in Rust 🎯

beginner
20 min

While Loop in Rust 🎯

Welcome to the Rust while Loop tutorial! In this lesson, we'll learn about one of the most fundamental control structures in Rust programming: the while loop. By the end of this lesson, you'll be able to write your own while loops to control the flow of your Rust programs.

What is a while Loop? 📝

A while loop is a control structure that repeatedly executes a block of code as long as a certain condition remains true. It's similar to the for loop, but with a while loop, you have more control over the loop's execution based on a specific condition.

Basic Syntax 💡

The basic syntax for a while loop in Rust is as follows:

rust
let mut counter = 0; while counter < 10 { println!("Counter: {}", counter); counter += 1; }

In the example above, we're initializing a variable counter with a value of 0. We then start a while loop that continues as long as counter is less than 10. Inside the loop, we're printing the value of counter and then incrementing it by 1.

Loop Condition 💡

The condition for a while loop is evaluated before each iteration. This means that if the condition is initially false, the loop will not execute at all. It's important to make sure your loop condition is correct to avoid infinite loops.

Here's an example of an incorrect loop condition:

rust
let mut counter = 10; while counter >= 10 { println!("Counter: {}", counter); counter += 1; }

In this example, the loop condition counter >= 10 is always true, causing an infinite loop.

Breaking out of a Loop 💡

To break out of a while loop, you can use the break keyword:

rust
let mut counter = 0; while counter < 10 { if counter == 5 { break; } println!("Counter: {}", counter); counter += 1; }

In the example above, we're breaking out of the loop once counter reaches the value of 5.

Quiz

Quick Quiz
Question 1 of 1

Which of the following is a valid `while` loop condition?

Practical Example 💡

Let's use a while loop to create a simple guessing game. The user will be asked to guess a random number between 1 and 100. The game will continue until the user guesses the correct number.

rust
use rand::Rng; use std::io; fn main() { let secret_number = rand::thread_rng().gen_range(1..=100); let mut guess = String::new(); println!("Guess a number between 1 and 100!"); while guess != secret_number.to_string() { print!("Enter your guess: "); io::stdin().read_line(&mut guess); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("Your guess was incorrect. Try again!"); } println!("Congratulations! You guessed the correct number!"); }

In this example, we're using the rand crate to generate a random number between 1 and 100. We then ask the user to guess the number and start a while loop that continues until the user guesses the correct number. Inside the loop, we read the user's input and parse it as a u32. If the input is not a valid number, we skip the current iteration and continue with the next one.

That's it for the while loop in Rust! With this knowledge, you can now create your own while loops to control the flow of your programs. Happy coding! 🎉