Switch in Go

Switch on a value

A switch compares one value against a list of cases and runs the first case that matches. It reads better than a long chain of if and else if statements when every branch tests the same value.

package main import "fmt" func main() { day := 3 switch day { case 1: fmt.Println("Monday") case 2: fmt.Println("Tuesday") case 3: fmt.Println("Wednesday") default: fmt.Println("Another day") } }

go run main.go

Wednesday

The default branch runs when no case matches. It is optional, but adding it documents what should happen with unexpected input.

No fallthrough by default

Unlike C, Go cases do not fall through into the next case. When a case body finishes, the whole switch ends, so you never need a break at the end of a case.

package main import "fmt" func main() { day := 6 switch day { case 6, 7: fmt.Println("Weekend") case 1: fmt.Println("Monday") default: fmt.Println("Workday") } }

One case can list several comma separated values, which keeps weekday and weekend style groupings short. The rare fallthrough keyword exists for the exceptional situation when the next case body must run as well, but most programs never use it.

Switch with initializer

Like an if statement, a switch can declare a short lived variable right in its header. The variable exists only inside the switch, which keeps the surrounding scope clean.

package main import "fmt" func main() { switch n := 7 % 2; n { case 0: fmt.Println("Even") default: fmt.Println("Odd") } }

A switch without any tag value is also legal: it behaves like a tidy if and else chain where each case holds a condition. Use the tagged form for values and the untagged form for conditions.

Type switches

A type switch inspects the dynamic type of an interface value instead of its content. Each case names a type, and inside that case the switched variable already has the concrete type.

package main import "fmt" func main() { var v any = "hello" switch t := v.(type) { case int: fmt.Println("int:", t) case string: fmt.Println("string:", t) default: fmt.Println("unknown type") } }

Type switches are the classic way to handle values of unknown shape, for example decoded data fields or plugin arguments. Keep the default branch so new types fail loudly instead of silently.

Next: Loops with for

Article author: Arthur Isaev