从零开始Go之条件语句

If

示例:文件读取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main

import (
"fmt"
"io/ioutil"
)

func main() {
const filename = "abc.txt"
contents, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s\n", contents)
}
}

首先,Go语言中是可以拥有多个返回值的。其次,if 条件语句没有用 () 包裹

程序优化写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
"fmt"
"io/ioutil"
)

func main() {
const filename = "abc.txt"
if contents, err := ioutil.ReadFile(filename); err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s\n", contents)
}
}

switch

switch 中没有 break,程序自动 break,使用 fallthrough 取消自动 break

示例:成绩判断

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
package main

import "fmt"

func grade(score int) string {
g := ""
switch {
case score < 0 || score > 100:
panic("分数异常")
case score < 60:
g = "F"
case score < 80:
g = "C"
case score < 90:
g = "B"
case score <= 100:
g = "A"
}

return g
}

func main() {
fmt.Println(grade(10),
grade(70),
grade(85),
grade(100),
)
}

触发 panic 会中止程序执行