How To Restart A For Loop In Go - Freshman.tech

Restart a for..range loop

There’s no way to reset a for..range loop in Go. However, you can use the goto keyword with a label to achieve a similar effect by starting the iteration again from the beginning. Here’s how to do it:

1package main 2 3import "fmt" 4 5func main() { 6 slice := []int{1, 2, 3, 4, 5} 7 8 var count int 9loop: 10 for _, v := range slice { 11 fmt.Println(v) 1213 count++ 14 if count == 2 { 15 goto loop 16 } 17 } 18}

In the above snippet, the for..range loop is given a label (loop, but it can be any name you want). Inside the loop, the goto keyword is used to break out of the loop once a certain condition is achieved. This moves control back to line 10 which effectively starts the loop from the beginning.

Output
1 2 1 2 3 4 5

Restart a standard for loop

In the snippet below, a traditional for loop is used to iterate over a slice of integers. When it’s time to reset the loop, the iterator (i) is set to -1. On the next iteration, i will be incremented before the loop body is executed (i++) which yields 0 causing the loop to have the effect of starting from the beginning.

package main import "fmt" func main() { slice := []int{1, 2, 3, 4, 5} var count int for i := 0; i < len(slice); i++ { fmt.Println(slice[i]) count++ if count == 2 { i = -1 // restart from the beginning } } }

You can use this technique if you want the loop to start at any index other than zero. All you need to do is set i to one less the desired index.

Thanks for reading, and happy coding!

  • #golang

Tag » How To Restart Loop C++