Continue and Break in For loops in Go
If we want to skip onto the next element in succession in a for loop, we can use the continue
keyword:
1for _, el := range employees {
2 if !e.IsCurrent {
3 continue
4 }
5 e.PrintCheck()
6}
When we need to terminate the loop early, we can use the break
keyword:
1for _, e := range employees {
2 if MoneyLeft() <= 0 {
3 fmt.Println("Oops, out of cash!")
4 break
5 }
6 ... // otherwise, print check
7}
As soon as Go encounters a break statement, it immediately stops the loop and jumps to the code immediately following the closing brace at the end of the for statement.
References
#programming #loops #range #break #init #flow #assignments #continue #repeat #for #infinite #statement #golang #post