go语言专门用于多条件分支语句。
这里有个基本的switch语句。
在同一个case语句中,可以用逗号分隔不同的条件。在这个例子中,我们使用默认的default语句。
没有表达式的switch语句可以替代if/else语句。这里我们显示了case表达式可以不是常量。
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
|
package main
import "fmt"
import "time"
func main() {
i := 2
fmt.Print("write ", i, " as ")
switch i {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
fmt.Println("it's the weekend")
default:
fmt.Println("it's a weekday")
}
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("it's before noon")
default:
fmt.Println("it's after noon")
}
}
|
$ go run switch.go
write 2 as two
it's the weekend
it's before noon
原文地址: https://gobyexample.com/switch