Konubinix' opinionated web of thoughts

Get Out of Nested Go for Loop With Labels (Not Like Goto)

Fleeting

golang go

We can use labels to break out of an ongoing loop. All we need to do is to create a label that points to the intended segment of the code. Here is an example.

package main

import ( “fmt” )

func main() { outside:                             / declare the label for i := 0; i<2; i++ { for j := 0; j<2; j++ { if i < j { break outside           / break to that label } fmt.Println(i, j) } }

// prints 0 0

}

https://golangdocs.com/for-loop-in-golang