流程控制结构主要包括分支结构、循环结构、标签跳转。
分支结构
if语句
1
2
3
4
5
6
7
|
if init_statement; control_statment1 {
statements
}else if control_statment2 {
statements
}else {
statements
}
|
init_statement在整个语句中只会被执行一次,且该语句中声明的变量的作用域是整个语句块。参照下面的示例:
1
2
3
4
5
6
7
8
9
10
11
|
if score := getScore(); score >= 90 {
fmt.Printf("score:%d grade:A\n", score)
} else if score >= 80 {
fmt.Printf("score:%d grade:B\n", score)
} else if score >= 70 {
fmt.Printf("score:%d grade:C\n", score)
} else if score >= 60 {
fmt.Printf("score:%d grade:D\n", score)
} else {
fmt.Printf("score:%d grade:E\n", score)
}
|
switch语句
1
2
3
4
5
6
7
8
|
switch init_statement; value_to_check {
case case_1:
statements
case case_2:
statements
default:
statements
}
|
-
Golang的switch不需要在每个case后面添加break语句,相当于默认就有,如果不需要break,则需要手动添加fallthrough
语句。
-
当使用value_to_check
时,case语句需要是一个值,且支持和value_to_check
进行相等比较。
-
当省略value_to_check
时,相当于和true
进行比较。
-
switch可以和xxx.(type)
组合进行类型判断。
1
2
3
4
5
6
7
8
|
switch input := getInput(); input {
case "Y":
fmt.Println("Accept")
case "N":
fmt.Println("Refuse")
default:
fmt.Printf("Bad input")
}
|
1
2
3
4
5
6
7
8
9
10
11
12
|
switch score := getScore(); {
case score >= 90:
fmt.Printf("score:%d grade:A\n", score)
case score >= 80:
fmt.Printf("score:%d grade:B\n", score)
case score >= 70:
fmt.Printf("score:%d grade:C\n", score)
case score >= 60:
fmt.Printf("score:%d grade:D\n", score)
default:
fmt.Printf("score:%d grade:E\n", score)
}
|
循环结构
Golang只有一种循环结构就是for循环:
1
2
3
4
5
6
7
8
|
//一般形式
for init_statement; condition_statement; post_statement {
statements
}
//for...range...形式,支持数组、切片、map、通道等
for k, v := range range_able_object {
statements
}
|
其中的init_statement
、condition_statement
、post_statement
都是可以省略的,语句可省分号不可省。
在循环结构中如果需要中途退出循环,需要使用break
语句或者continue
语句,且只能跳出语句所在层级的循环。
标签跳转
标签是指添加在语句最前面的表示语句位置的标识。
标签可以和goto
、break
、continue
语句组合,实现跳转到对应标签功能。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
const size int = 10
var m [size][size]int
for x := 0; x < size; x++ {
for y := 0; y < size; y++ {
m[x][y] = rand.Intn(100)
}
}
MapLoop:
for x := 0; x < size; x++ {
for y := 0; y < size; y++ {
if m[x][y] < 10 {
fmt.Printf("find pos [%d, %d]\n", x, y)
break MapLoop
}
}
}
|