Switch
Switch statements can test against several values:
// Output: 4,5,6
func main() {
switch 4 {
case 1, 2, 3:
fmt.Println("1,2,3")
case 4, 5, 6:
fmt.Println("4,5,6")
default:
fmt.Println("Another")
}
}
Switch statement's tests must be unique!. Next example will fail:
// Build would fail
func main() {
i := 4
switch i {
case 1, 2, 3:
fmt.Println("first case")
case 3, 4, 5: // Here is 3 met second time
fmt.Println("second case")
default:
fmt.Println("default")
}
}
Switch tag can contain initializer:
// Output: Another
func main() {
switch i := 2 + 3; i {
case 1:
fmt.Println("1")
default:
fmt.Println("Another")
}
}
Switch can contain no tag but case must contain statement:
// Output: 1,2,3
func main() {
i := 3
switch {
case i < 4:
fmt.Println("1,2,3")
case i < 7:
fmt.Println("4,5,6")
default:
fmt.Println("Another")
}
}
To fall through switch tests include fallthrough keyword:
// Output:
// 1,2,3
// 4,5,6
func main() {
i := 3
switch {
case i < 4:
fmt.Println("1,2,3")
fallthrough
case i < 7:
fmt.Println("4,5,6")
default:
fmt.Println("Another")
}
}