Skip to content

Go break & continue in switch

kuchaguangjie edited this page Jul 25, 2018 · 1 revision

break & continue in switch

switch in Go, is a bit different from C or Java, one obvious difference is break.

break

Rules:

  • break is not needed for each case.
    Because go's switch stops on first matching, won't execute the following ones.
  • If break is added in a case or default.
    Then it will terminate the switch statement.

continue

Rules:

  • continue can't be applied on switch statement.
  • If the switch is within a loop, then a continue could be added, to apply on the outer loop.
  • If the switch is not within a loop, then can't add a continue inside it, it's syntax error.

Example

switch_learn.go:

package main

import (
	"fmt"
)

// check how "break" works on switch,
func breakTest() {
outer:
	for i := 0; i < 10; i++ {
		switch i {
		case 3, 6, 9:
			fmt.Printf("%d, printable by 3\n", i)
		case 0, 5:
			fmt.Printf("%d, printable by 5\n", i)
		case 4:
			break // this will break the switch, not the outer for,
		case 8:
			break outer // this will break the outer loop,
		default:
			fmt.Printf("%d, other\n", i)
		}
	}
}

func main() {
	breakTest()
}

Execute:

go run switch_learn.go

Output:

0, printable by 5
1, other
2, other
3, printable by 3
5, printable by 5
6, printable by 3
7, other

Explanation:

  • 4 is not printed, due to the first break, it terminate that switch, but not the outer for loop.
  • 8 and 9 is not printed, due to the second break outer, it terminate the outer for loop, not just the switch.