1. package main
    2. import "fmt"
    3. func main() {
    4. //一楼
    5. num := 1
    6. switch num { //switch后面写的是变量本身
    7. case 1:
    8. fmt.Printf("按下的是%d", num)
    9. case 2:
    10. fmt.Printf("按下的是%d", num)
    11. case 3:
    12. fmt.Printf("按下的是%d", num)
    13. case 4:
    14. fmt.Printf("按下的是%d", num)
    15. }
    16. }

    图片.png

    其他特殊情况的default:

    1. package main
    2. import "fmt"
    3. func main() {
    4. //一楼
    5. num := 0
    6. switch num { //switch后面写的是变量本身
    7. case 1:
    8. fmt.Println("按下的是", num)
    9. case 2:
    10. fmt.Println("按下的是", num)
    11. case 3:
    12. fmt.Println("按下的是", num)
    13. case 4:
    14. fmt.Println("按下的是", num)
    15. default:
    16. fmt.Println("你在瞎按!!!!!")
    17. }
    18. }

    图片.png
    你会发现,跟其他语言不同,因为少了一个break关键字
    go语言保留了break关键字,跳出switch语言,不写,默认就包含。

    再来看看另外一个go语言的关键字,fallthrough
    fallthrough的意思就是不跳出switch语句,相当于没有写break。
    如下图所示:

    1. package main
    2. import "fmt"
    3. func main() {
    4. var num int
    5. fmt.Printf("请输入楼层数:")
    6. fmt.Scan(&num)
    7. //一楼
    8. switch num { //switch后面写的是变量本身
    9. case 1:
    10. fmt.Println("按下的是1楼")
    11. fallthrough
    12. case 2:
    13. fmt.Println("按下的是2楼")
    14. fallthrough
    15. case 3:
    16. fmt.Println("按下的是3楼")
    17. fallthrough
    18. case 4:
    19. fmt.Println("按下的是4楼")
    20. fallthrough
    21. default:
    22. fmt.Println("你在瞎按!!!!!")
    23. }
    24. }

    图片.png
    所以,fallthrough关键字的作用就是不跳出switch语句,后面的无条件执行。