Start learning free

LESSON 117 OF 348 · FOR LOOPS - LOOPING OVER ARRAYS

Infinite For Loops II in Rust in Rust

Lesson

We also use for loops to iterate over sequences like strings and arrays. We can run into problems when we manipulate a sequence while iterating on it.

For example, if we append elements to an array while iterating on it:

let mut fruits: Vec<&str> = vec!["banana", "orange"];

let mut i = 0;
while i < fruits.len() {
    fruits.push("kivi");
    i += 1;
}

Every time we enter this loop, we add a kivi item to the end of the array that we are iterating through.

As a result, we never make it to the end of the array. It keeps growing forever!

This is an infinite for loop. You can imagine that as programmers, we want to make sure we never write infinite loops as they make our program run forever and completely unusable.


Assignment
Follow the Coding Tutorial and let's practice with infinite for loops!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    Infinite For Loops 2 in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free