Go Language - Switch Statement
A switch statement is a shorter way to write a sequence of if-else statements. It runs the first case whose value is equal to the condition expression. The cases are evaluated from top to bottom, stopping when a case succeeds. If no case matches and there is a default case, its statements are executed.
Example 1:
package main
import "fmt"
func main() {
day := 6
switch day { case 1: fmt.Println("Sunday") case 2: fmt.Println("Monday") case 3: fmt.Println("Tuesday") case 4: fmt.Println("Wednesday") case 5: fmt.Println("Thursday") case 6: fmt.Println("Friday") case 7: fmt.Println("Saturday") }}
Output:
Example 2: break breaks the inner switch
package main
import "fmt"
func main() {
loop: for i := 0; i < 9; i++ { fmt.Printf("%d", i) switch { case i == 1: fmt.Println("start")
case i == 8: fmt.Println("end")
case i == 6: fmt.Println("stop") break loop
case i > 3: fmt.Println("sleeping..") break
default: fmt.Println("default..") } }}