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 a slice while iterating on it:
fruits := []string{"banana", "orange"}
for i := 0; i < len(fruits); i++ {
fruits = append(fruits, "kiwi")
}
Every time we enter this loop, we add a kiwi item to the end of the slice that we are iterating through.
As a result, we never make it to the end of the slice. 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.
Free plan: 30 tutor messages. PRO is unlimited.
