Fork me on GitHub

Golang之旅26_switch

switch语句的特点:

  • 拥有多个分支
  • switch后面可以不跟语句,在case的每个分支中直接添加
  • 需要有default语句
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
77
78
79
80
81
82
83
84
85
86
87
88
package main

import (
"fmt"
)

func eval(a, b int, op string) int{
var result int
switch op {
case "+":
result = a + b
case "-":
result = a - b
case "*":
result = a * b
case "/":
result = a / b
default:
panic("unsupport operator:" + op) // panic 自动报错机制
}
return result
}


func grade(score int ) string{
g := ""
switch { // switch 后面可以不跟表达式,直接在case中添加
case score < 0 || score > 100 :
panic(fmt.Sprintf("Wrong score: %d",score))
case score < 60:
g = "D"
case score < 80:
g = "C"
case score < 90:
g = "B"
case score < 100:
g = "A"
// default:
// panic(fmt.Sprintf("Wrong score: %d",score))
}
return g

}

func main(){
//猜手指
//finger := 3
//switch finger {
//case 1:
// fmt.Println("大拇指")
//case 2:
// fmt.Println("食指")
//case 3:
// fmt.Println("中指")
//case 4:
// fmt.Println("无名指")
//case 5:
// fmt.Println("小指")
//default:
// fmt.Println("无效输入")

////分支后面跟多个值
//number := 5
//switch number {
//case 1,3,5,7,9:
// fmt.Println("奇数")
//case 2,4,6,8,10:
// fmt.Println("偶数")
//default:
// fmt.Println("无效输入")
//}

result := eval(3, 5 ,"+")
fmt.Println(result)

fmt.Println(grade(87))

//分支后面跟表达式
number := 5
switch {
case number % 2 == 0 :
fmt.Println("hello python")
case number % 2 == 1:
fmt.Println("hello Go")
default:
fmt.Println("无效输入")
}
}

本文标题:Golang之旅26_switch

发布时间:2019年10月07日 - 19:10

原始链接:http://www.renpeter.cn/2019/10/07/Golang%E4%B9%8B%E6%97%8526-switch.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Coffee or Tea