Essential Go if, switch, goto  Suggest an edit

switch statement

A simple switch statement:

a := 1
switch a {
case 1, 3:
	fmt.Printf("a is 1 or 3\n")
case 2:
	fmt.Printf("a is 2\n")
	fmt.Printf("default: a is %d\n", a)
a is 1 or 3

Notice case can handle multiple values (1 and 3 in above example).


Unlike most other languages like C++ or Java, you don't have to use break to stop one case into continuing execution in following case.

Such default behavior is a frequent source of bugs.

Instead in Go you can ask for such behavior with fallthrough:

a := 1
switch a {
case 1:
	fmt.Printf("case 1\n")
case 2:
	fmt.Printf("caes 2\n")
case 1
caes 2

switch on strings

Switch in Go is more flexible than in languages like C++ or Java.

We can switch on strings:

s := "foo"
switch s {
case "foo":
	fmt.Printf("s is 'foo'\n")
case "bar":
	fmt.Printf("s is 'bar'\n")
s is 'foo'

empty switch expression

switch expression can be empty in which case case can be a boolean expression, not just a constant:

func check(n int) {
	switch {
	case n > 0 && n%3 == 0:
		fmt.Printf("n is %d, divisible by 3\n", n)
	case n >= 4:
		fmt.Printf("n is %d (>= 4)\n", n)
		fmt.Printf("default: n is %d\n", n)

n is 3, divisible by 3
n is 4 (>= 4)
n is 6, divisible by 3
default: n is 1

order of evaluation of case

What happens if more than one case statement evaluates as true?

In the above example 6 matches both n > 0 && n%3 == 0 expression and n ≥ 4 expression.

As you can see, only one case is executed, the one defined first.

assignment in switch

switch n := rand.Intn(9); n {
case 1, 2, 3:
	fmt.Printf("case 1, 2, 3: n is %d\n", n)
case 4, 5:
	fmt.Printf("case 4, 5: n is %d\n", n)
	fmt.Printf("default: n is %d\n", n)
case 1, 2, 3: n is 1

switch on type of variable

Switch can also dispatch based on type of the value.

  ↑ ↓ to navigate     ↵ to select     Esc to close