How To Restart A For Loop In Go - Freshman.tech
Maybe your like
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.
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++
-
How Can I Restart While Loop After Certain Condition (if) Satisfied In C++?
-
How To Restart Loop Again? - C++ Forum
-
How Can I Restart A Loop: C++ - For Beginners
-
C++ Loop Help To Restart To Beginning Of Program - C Board
-
Restarting A While Loop Without Finishing The Remaining Code.
-
How To Restart A Loop In Python? - Finxter
-
How To Use A While Loop To Restart A Game - Quora
-
How To Restart Void Loop If Condition Is Met - Arduino Stack Exchange
-
C++ How To Restart The Loop If User Just Presses Enter Or If The Input Is ...
-
JavaScript: Continue Statement - TechOnTheNet
-
How Do I Restart A Function From Within Itself? - Codecademy
-
Exit(0); Restart Loop - Programming Questions - Arduino Forum
-
How Can I Restart While Loop After Certain Condition (if) Satisfied In C++?
-
Going To Start Of A Loop - Scripting Support - DevForum | Roblox