基础知识 - 控制语句
if switch
if
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17const filename = "a.txt"
contents,err :=ioutil.ReadFile(filename)
if err != nil {
fmt.Println(err)
}else {
fmt.Printf("%s",contents)
}
//简写版本
const filename = "a.txt"
if contents,err :=ioutil.ReadFile(filename) ; err != nil {
fmt.Println(err)
}else {
fmt.Printf("%s",contents)
}
//只在if 作用域内
switch
switch 默认带上braek 除非显式指定fallthrough
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
30var res int
switch op {
case "+":
res = a+b
case "-":
res = a-b
case "*":
res = a*b
case "/":
res = a/b
fallthrough
case "p":
fmt.Println("hello")
default:
panic("undefine opcode:" + op)
}
fmt.Println(res)
//hello
//0
//不携带参数
var res int
flag := rand.Int()
switch {
case op == "+":
res = a + b
case flag > 10000:
res = 1
//...
}
fmt.Println(res)
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 SHIELD!
评论