Switch expressions
If we want to take conditional actions on the value of some variable, switch
gives us a handy shortcut: the switch expression:
1switch x {
2case 1:
3 fmt.Println("one")
4case 2:
5 fmt.Println("two")
6case 3:
7 fmt.Println("three")
8}
We say this statement switches on x, that is, the different cases represent different possible values of the switch expression x. You can use any Go expression here instead of x, providing that it evaluates to a value of the same type as your switch cases.
You can supply multiple values in the same case, as a comma-separated list. If any of the values match, the case will be triggered:
1switch x {
2 case 1, 2, 3:
3 fmt.Println("one, two, or three")
4...
5}
One important difference from C is that Go only runs the selected case, not all cases that follow (so you don’t need a break
statement).
Another difference is that Go’s switch cases need not be constants, and the values involved need not be integers.
Switch with no condition is the same as switch true
, and can be a clean way to write long if-else chains
References
- John Arundel, For the Love of Go
#switch #flow #golang #cascade #path #break #value #happy #multiple #expression #if #fallthrough #condition #programming