break
A break
statement terminates execution of the innermost for
, switch
, or select
statement within the same function.
break
is unlabled, it will break out of the nearest enclosing loopbreak
is labeled, it will break out of the specified label loopOuterLoop: for i = 0; i < n; i++ { for j = 0; j < m; j++ { switch a[i][j] { case nil: state = Error break OuterLoop case item: state = Found break OuterLoop } } }
Example of break
which terminates inner switch
.
package main import "fmt" func main() { myloop: for x := 0; x < 7; x++ { // always print the current iteration index fmt.Printf("%d", x) // inner switch inside the loop switch { case x == 1: fmt.Println("start") case x == 5: fmt.Println("stop") // breaks out of the loop break myloop case x > 2: fmt.Println("crunching..") // break, with no effect due to missing label break default: // default acts like a `catch` all and will only run when non of the `case` covers fmt.Println("idling..") } } } /* Console output 0idling.. 1start 2idling.. 3crunching.. 4crunching.. 5stop */
continue
A continue
statement begins the next iteration of the innermost enclosing for
loop by advancing control to the end of the loop block.
The for
loop must be within the same function.
RowLoop: for y, row := range rows { for x, data := range row { if data == endOfRow { continue RowLoop } row[x] = data + bias(x, y) } }