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
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
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
Last updated