Break and Continue

With break you can quit loops early. By itself, breakbreaks the current loop.

  1. for i := 0; i < 10; i++ {
  2. if i > 5 {
  3. break 1
  4. }
  5. fmt.Println(i) 2
  6. }

Here we break the current loop 1, and don’t continue with thefmt.Println(i) statement 2. So we only print 0 to 5. With loops within loopyou can specify a label after break to identify which loop to stop:

  1. J: for j := 0; j < 5; j++ { 1
  2. for i := 0; i < 10; i++ {
  3. if i > 5 {
  4. break J 2
  5. }
  6. fmt.Println(i)
  7. }
  8. }

Here we define a label “J” 1, preceding the for-loop there. When we usebreak J 2, we don’t break the inner loop but the “J” loop.

With continue you begin the next iteration of theloop, skipping any remaining code. In the same way as break, continue alsoaccepts a label.