Combining Loops and Conditionals
You've now learned about the two fundamental pillars of control flow: conditionals (if) and loops (loop, while, for). The real power comes when you start combining these two concepts to build more complex and interesting logic. In this article, we'll explore some common patterns for using if expressions inside loops.
Iterating over Collections
In the previous article, we introduced the for loop and used it to iterate over a range of numbers. The true power of for loops, however, comes from their ability to iterate over collections like arrays, vectors, and more. This is the most common and idiomatic way to work with collections in Rust.
Loops: `for` loops and the `..` range operator
We've explored loop for infinite loops and while for conditional loops. Now, we'll look at the most common and often most powerful loop in Rust: the for loop. for loops are excellent for executing a block of code a specific number of times and for iterating over collections.
Loops: `loop` for infinite loops
Now that you've mastered if expressions, it's time to explore another fundamental control flow concept loop.
Loops: `while` loops
In the previous article, we learned how to create infinite loops with the loop keyword. While loop is useful, it's often more common to loop while a certain condition is true. For this, Rust provides the while loop.
Project: Guessing Game (Part 3)
Welcome to the final part of our Guessing Game project! In Part 2, we added the core logic for comparing the user's guess to the secret number. In this article, we'll add the final polish to our game by handling invalid input gracefully and improving the looping mechanism.