switch


Compared to other programming languages (such as C), Go‘s switch-case statement doesn’t need explicit “break“, and not have fall-though characteristic. Take the following code as an example:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func checkSwitch(val int) {
  6. switch val {
  7. case 0:
  8. case 1:
  9. fmt.Println("The value is: ", val)
  10. }
  11. }
  12. func main() {
  13. checkSwitch(0)
  14. checkSwitch(1)
  15. }

The output is:

  1. The value is: 1

Your real intention is the “fmt.Println("The value is: ", val)“ will be executed when val is 0 or 1, but in fact, the statement only takes effect when val is 1. To fulfill your request, there are 2 methods:

(1) Use fallthrough:

  1. func checkSwitch(val int) {
  2. switch val {
  3. case 0:
  4. fallthrough
  5. case 1:
  6. fmt.Println("The value is: ", val)
  7. }
  8. }

(2) Put 0 and 1 in the same case:

  1. func checkSwitch(val int) {
  2. switch val {
  3. case 0, 1:
  4. fmt.Println("The value is: ", val)
  5. }
  6. }

switch can also be used as a better if-else, and you may find it may be more clearer and simpler than multiple if-else statements.E.g.:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func checkSwitch(val int) {
  6. switch {
  7. case val < 0:
  8. fmt.Println("The value is less than zero.")
  9. case val == 0:
  10. fmt.Println("The value is qual to zero.")
  11. case val > 0:
  12. fmt.Println("The value is more than zero.")
  13. }
  14. }
  15. func main() {
  16. checkSwitch(-1)
  17. checkSwitch(0)
  18. checkSwitch(1)
  19. }

The output is:

  1. The value is less than zero.
  2. The value is qual to zero.
  3. The value is more than zero.