switch

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main

import (
	"fmt"
	"math/rand"
)

func main() {
	//----------- 表达式选择 ------------
	fmt.Println("----------- 表达式选择 ------------")
	// 没有变量, 类似 if else
	score := rand.Intn(101)
	switch { // 相当于 switch true {
	case score < 60:
		fmt.Println("E")
	case 60 <= score && score <= 69:
		fmt.Println("D")
	case 70 <= score && score <= 79:
		fmt.Println("C")
	case 80 <= score && score <= 89:
		fmt.Println("B")
	case 90 <= score && score <= 100:
		fmt.Println("A")
	}

	// 有变量
	i := rand.Intn(3)
	switch i {
	case 0:
		fmt.Println("i is 0.")
	case 1, 2:
		fmt.Println("i is 1 or 2.")
	default:
		fmt.Println("i is unknown.")
	}

	// 有变量, 且有新定义局部变量
	switch j := rand.Intn(3); j {
	case 0:
		fmt.Println("j is 0.")
	case 1, 2:
		fmt.Println("j is 1 or 2.")
	default:
		fmt.Println("j is unknown.")
	}

	// 有变量, 且有新定义局部变量
	switch score := rand.Intn(101); { // 相当于 switch score := rand.Intn(101); true {
	case score < 60:
		fmt.Println("E")
	case 60 <= score && score <= 69:
		fmt.Println("D")
	case 70 <= score && score <= 79:
		fmt.Println("C")
	case 80 <= score && score <= 89:
		fmt.Println("B")
	case 90 <= score && score <= 100:
		fmt.Println("A")
	}

	//----------- 类型选择 ------------
	fmt.Println("----------- 类型选择 ------------")
	var x any
	x = 28

	switch x.(type) { // 这里若使用 switch x.(type); true { , 则会编译报错
	case int, int8, int16, int32, int64:
		fmt.Println("x's type is ints.")
	case uint, uint8, uint16, uint32, uint64:
		fmt.Println("x's type is uints.")
	case float32, float64:
		fmt.Println("x's type is floats.")
	default:
		fmt.Println("x's type is unknown.")
	}
}
最后修改 March 10, 2024: 更新 (ddf4687)