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
}

本文网址: https://golangnote.com/topic/35.html 转摘请注明来源

Related articles

Golang 实现 10 进制转 N 进制

给定一个不没有重复字符的字符串,如 `[0-9,a-z]`,把一个 10 进制数字转为,该字符集的字符串。应用场合如汽车牌、顺序计数。...

Golang 单实例实现网站多域名请求

有时候写网站,为了统一的后端,把不同业务都集中到一个后端,这时就需要处理多域名的请求,在 Go http server 里实现很简单,只需把不同域名映射到不同的 `http.Handler`。...

golang snappy 的使用场合

google 自家的 snappy 压缩优点是非常高的速度和合理的压缩率。压缩率比 gzip 小,CPU 占用小。...

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

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 1ms