GolangNote

Golang笔记

GoLang switch 控制语句的灵活应用

Permalink

与我们以前接触过的switch 控制语句不同,GoLang 的switch 语句使用更灵活。

GoLang switch 控制语句的灵活应用

简单使用示例

Go: switch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
score := 79
switch score / 10 {
    case 9:
        rz = "优秀"
        fallthrough  // 表示继续执行下面的Case而不是退出Switch
    case 8:
        rz = "良好"
    case 7:
        rz = "一般"
        break //可以添加
    case 6:
        rz = "及格"
    default:
        rz = "不及格"
 }

使用说明:

  • switch 的判断条件可以是任何数据类型
  • 在每个case 里可以不用break 退出,默认退出
  • 可以通过关键字 fallthroughswitch 不退出,而继续判断下面的case

如果多个匹配结果所对应的代码段一样,则可以在一个case中并列出所有的匹配项

Go: switch
1
2
3
4
5
6
7
8
switch ch {
    case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
        cl = "Int"
    case 'A', 'B', 'C', 'D',  'a', 'b', 'c', 'd', 'e':
        cl = "ABC"
    default:
        cl = "Other Char"
}

switch可以没有表达式,在 Case 中使用布尔表达式,这样形如 if-else

Go: switch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
func GetConstellation(month, day int) (star string) {
    switch {
    case month <= 0, month >= 13, day <= 0, day >= 32:
        star = "-1"
    case (month == 1 && day >= 20), (month == 2 && day <= 18):
        star = "水瓶座"
    case (month == 2 && day >= 19), (month == 3 && day <= 20):
        star = "双鱼座"
    case (month == 3 && day >= 21), (month == 4 && day <= 19):
        star = "白羊座"
    case (month == 4 && day >= 20), (month == 5 && day <= 20):
        star = "金牛座"
    case (month == 5 && day >= 21), (month == 6 && day <= 21):
        star = "双子座"
    case (month == 6 && day >= 22), (month == 7 && day <= 22):
        star = "巨蟹座"
    case (month == 7 && day >= 23), (month == 8 && day <= 22):
        star = "狮子座"
    case (month == 8 && day >= 23), (month == 9 && day <= 22):
        star = "处女座"
    case (month == 9 && day >= 23), (month == 10 && day <= 22):
        star = "天秤座"
    case (month == 10 && day >= 23), (month == 11 && day <= 21):
        star = "天蝎座"
    case (month == 11 && day >= 22), (month == 12 && day <= 21):
        star = "射手座"
    case (month == 12 && day >= 22), (month == 1 && day <= 19):
        star = "魔蝎座"
    }
    return
}

Related articles

Write a Comment to "GoLang switch 控制语句的灵活应用"

Submit Comment Login
Based on Golang + fastHTTP + youdb | go1.16 Processed in 1ms