switch statement

suggest change

A simple switch statement:

main.go

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

Output:

a is 1 or 3

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

fallthrough

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:

main.go

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

Output:

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:

main.go

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

Output:

s is 'foo'

empty switch expression

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

main.go

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)
	default:
		fmt.Printf("default: n is %d\n", n)
	}
}

	check(3)
	check(4)
	check(6)
	check(1)

Output:

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

main.go

	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)
	default:
		fmt.Printf("default: n is %d\n", n)
	}

Output:

case 4, 5: n is 4

switch on type

If you have an interface value, you can switch based on type of underlying value:

main.go

func printType(iv interface{}) {
	// inside case statements, v is of type matching case type
	switch v := iv.(type) {
	case int:
		fmt.Printf("'%d' is of type int\n", v)
	case string:
		fmt.Printf("'%s' is of type string\n", v)
	case float64:
		fmt.Printf("'%f' is of type float64\n", v)
	default:
		fmt.Printf("We don't support type '%T'\n", v)
	}
}

func main() {
	printType("5")
	printType(4)
	printType(true)
}

Output:

'5' is of type string
'4' is of type int
We don't support type 'bool'

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents