Create a loop in Rust

InstructorPascal Precht

Share this video with your friends

Send Tweet

This lesson shows how to use a Rust loop to run a program infinitely.

J. Matthew
~ a year ago

Worth noting how to exit out of the infinite loop, haha. You can do the usual "cancel process" command (CTRL + c on Mac), but entering an invalid number will also work, as it will trigger the exit call set up in the previous lesson.

I am curious why this simple loop option even exists. Given Rust's aggressive emphasis on writing safe code, why does it make it so easy to write an infinite loop? More to the point, is there any scenario where that would be the right thing to do?

Pascal Prechtinstructor
~ a year ago

Hi Matthew,

as always, good question. So it turns out that loop is really useful for cases where you would otherwise for example use a while(true) {} construct. In addition, Rust doesn't have a do {} while() loop, so loop might come in handy for such cases as well.

For more insights, have a look at this StackOverflow answer:

loop is often used for loops where we want to break in the middle of the loop's body. That is, you want to do something before testing any condition, then exit the loop if some condition is met, then do something else that must only be done after testing the condition, then repeat. In other languages, this is often rendered as while (true) or for (;;). This situation is common enough that Rust decided to embrace this pattern by reserving a keyword to declare loops that have no entry condition.

Source: https://stackoverflow.com/questions/39439088/usability-of-infinite-loop-in-rust

Hope this helps!

J. Matthew
~ a year ago

For more insights, have a look at this StackOverflow answer

Aha, I didn't think of those use-cases, but in retrospect they make perfect sense. Thanks! Another comment on that Stack Overflow post mentions using an infinite loop to continue creating "turns" in a game as long as the player desires; that reminded me of the Update function in Unity's C# scripts, which in turn reminded me of the draw function in Processing; openFrameworks also has similar functions. All of these functions are fired automatically and repeatedly on some interval (usually frame-based) for the life of the application, which makes them, by definition...infinite loops*. D'oh! It's obvious now, but I never thought of them that way before.

*Or called by one, anyway.

This makes me think about the intricacies of implementation. Another way to keep some bit of functionality going until some condition were satisfied would be to use recursion, yet I know that carries the risk of, er, "stack overflow," a problem I understand (vaguely) that the loop avoids.