Rust By Example: Loop and While Loops

Опубликовано: 15 Апрель 2026
на канале: Stephen Blum
178
3

Rust gives you a loop keyword for making an infinite loop, which means the computer continues repeating until a certain condition is fulfilled. It sounds scary, but infinitive loops, when used right, are very influential. Commonly used in computing, loops allow a computer to quickly repeat procedures.

The trick is to always have an exit point to prevent the computer from getting stuck. For instance, if you're designing a video game, your loop makes frames as fast as it can. The exit point can be breaking the current loop to get to a different loop like a menu loop or closing the program completely.

You can use the break statement to stop a loop in its tracks, and the continue statement to skip some code and get back to the top of the loop immediately. Let's look at an example using a mutable variable count. We initialize it to zero and place it inside an infinite loop.

Looking risky so far, right? We increase the count by one every time we start the loop. We check if count equals three.

If yes, we print "it's three" and go back to the top, skipping the other statements. If not, we move down and print the current count. We then check if count is five and if it is, we exit the loop.

Apart from all the checking and breaking, we can also assign a variable to a loop and capture the resulting data. What do we get with this? A direct control over where your loop control flow should go.

It's a key strategy that maintains the ease, simplicity, and efficiency you need while working on nested looping. But remember, with all this power, you should play safely. Always ensure that there's a guaranteed break to stop the loop if the exit condition isn’t met.

Another way to ensure safety while looping is the use of the while keyword. This runs a loop only when a specified condition is true, giving you an extra layer of protection. But remember, even with a condition in place, a while loop can still turn into an infinite loop if the condition for termination of the loop is not met.

For instance, if we comment out the increment, the loop will run indefinitely since the number will always be less than 101.