if/else, switch, the lone for loop, break, continue.
switch and Type Switch
Go's switch is safer than C's — no fallthrough by default, no need for break.
It also doubles as a way to inspect a value's runtime type.
Value switch
go playground
Loading...
A case can list multiple values separated by commas. Order doesn't matter — the
first match wins.
No fallthrough — but you can opt in
switch n {
case 1:
fmt.Println("one")
fallthrough
case 2:
fmt.Println("two or one")
}
fallthrough jumps to the next case body, ignoring its condition. Use sparingly.
Switch with no condition
A switch without an expression is a cleaner if / else if chain:
switch {
case n < 0:
fmt.Println("negative")
case n == 0:
fmt.Println("zero")
default:
fmt.Println("positive")
}
Switch with init
Like if, you can declare a variable in the switch line:
switch tag := getTag(); tag {
case "v1":
...
}
Type switch
Use switch v := x.(type) to ask "what is x?" — common with interface{} /
any values. The variable v is rebound to the matched type inside each case.
go playground
Loading...
We come back to type assertions properly in chapter 12.
In Go's `switch`, what happens after a matched case runs (no `fallthrough`)?