Loops in Rust
# CHAPTER 8
Loops in Rust
1. Chapter Introduction
If you need to print a user's profile 100 times, you shouldn't copy and paste theprintln! macro 100 times. You use loops. Rust provides three different types of loops to handle repetitive tasks: loop, while, and for. In this chapter, we will learn when and how to use each one, as well as how to exit loops early.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Create infinite loops using
loop.
-
Create conditional loops using
while.
-
Iterate over collections and ranges using
for.
-
Control loop flow using
breakandcontinue.
-
Return values from a
loop.
3. The loop Keyword
The loop keyword is unique to Rust. It creates an infinite loop that will run forever until you explicitly tell it to stop. This is often used for game engines or servers listening for network requests constantly.
You stop a loop using the break keyword.
Returning Values from a Loop!
Because everything in Rust is an expression, loop can actually return a value when you break!
4. The while Loop
A while loop runs code *as long as a condition evaluates to true*. The condition is checked at the beginning of each iteration.
5. The for Loop (The Most Commonly Used)
The for loop is the safest and most common loop in Rust. It is used to execute code for each item in a collection (like an Array or Tuple) or a specific range of numbers.
A. Looping through a Range
We use the .. syntax to define a range. 1..5 means 1 up to (but not including) 5.
B. Looping through an Array
Unlike while loops (which can accidentally cause "index out of bounds" panics if you calculate the array length wrong), for loops iterate safely.
6. The continue Keyword
While break exits the loop entirely, continue skips the rest of the current iteration and jumps straight to the next one.
7. Mini Project: Multiplication Table Generator
Let's generate a multiplication table for the number 5 using afor loop.
8. Common Mistakes
-
Infinite Loops by Accident: Creating a
loopor awhileloop but forgetting to update the condition variable (e.g., forgettingfuel -= 1), causing the program to freeze in an infinite loop.
-
Off-by-One Errors in Ranges: Thinking
1..10includes 10. It only goes up to 9. You must use1..=10to include the 10.
9. Best Practices
-
Default to
forloops: If you are iterating over an array or a known sequence of numbers, always usefor. It prevents bugs and is highly optimized by the compiler. Only useloopwhen you truly need an infinite retry mechanism.
10. Exercises
-
1.
Write a
whileloop that counts down from 10 to 1 and prints "Liftoff!".
-
2.
Write a
forloop that iterates through an array of three names and prints "Hello, [name]".
11. MCQs with Answers
Which keyword creates an unconditional infinite loop?
How do you exit a loop or while loop completely?
Which keyword skips the current iteration and moves to the next one?
loop keyword return a value?
a) Yes, by passing a value after the break keyword b) No, loops are strictly statements
Answer: a) Yes, by passing a value after the break keyword.
When does a while loop evaluate its condition?
What does the range 1..5 represent in a for loop?
How do you make a range inclusive of the upper bound?
Why is iterating over an array with a for loop considered safer than a while loop?
Which loop is best for a game server that must run continuously until manually shut down?
How do you safely iterate over an array named users using a for loop?
12. Interview Questions
-
Q: Explain why you can return a value from a
loopexpression but not awhileexpression. (Hint:whilemight never run if the condition is false immediately, so it can't guarantee returning a value).
-
Q: Contrast the use-cases for
loop,while, andfor.
13. Summary
Loops allow developers to automate repetitive tasks efficiently. Whileloop provides brute-force infinite repetition and while offers conditional looping, the for loop stands out as Rust's safest and most powerful tool for traversing data structures and numeric ranges.