switch statement

suggest change

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 4, 5: n is 4

switch on type

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

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)
		fmt.Printf("We don't support type '%T'\n", v)

func main() {
'5' is of type string
'4' is of type int
We don't support type 'bool'

Feedback about page:

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

Table Of Contents