17. Switch

Switch Statement

When there are multiple branches, if...else code can get more verbose. Switch statement provide more efficient way to express multiple branches. Semantic for switch statement is

switch condition {
    case x: 
        code to execute
    case y:
        code to execute   
    default:
        code to execute     
}

When one of the case statement is matched, that code is executed. Default block is executed when there is no matching case.

No Fall-through

One of the difference switch statement has with other programming languages, is that if one of the case is matched, only that code is executed and switch statement break automatically. This means that cases do not fall-though automatically for switch statement in Go.

main.go
i := 2
switch i {
case 1:
	fmt.Println("i is one")
case 2:
	fmt.Println("i is two")
case 3:
	fmt.Println("i is three")
case 4:
	fmt.Println("i is four")
}

Only case 2 will be executed.

Switch without expression

We can also define without any expression and case statement can take care of evaluating condition.

main.go
dayOfWeek := 6
switch {
case dayOfWeek == 6 || dayOfWeek == 7:
	fmt.Println("It's weekend!")
case dayOfWeek < 6 && dayOfWeek > 0:
	fmt.Println("It's weekday!")
default:
	fmt.Println("You are not on Earth!")
}

Last updated