12.流程控制语句
a.if else语句块
基本语法:
1: if condition {
2: // do something
3: }
1: if condition {
2: // do something
3: }else if condition {
4: // do something
5: }else {
6: // do something
7: }
1: if statement; condition {
2: // do something
3: }
b.for语句
Go语言只有一种循环:
1: for initialisation; condition; post {
2: }
break终止循环
continue终止本次循环
其他几种写法例:
1: func main() {
2: i:=0
3: for ;i<=10;{
4: fmt.Printf("%d ", i)
5: i += 2
6: }
7: }
8: func main() {
9: i:=0
10: for i<=10 {
11: fmt.Printf("%d ", i)
12: i += 2
13: }
14: }
15: func main() {
16: for no,i := 10;i<=10&&no<=19;i,no=i+1,no+1 {
17: fmt.Printf("%d*%d=%d ",no,i,no*i)
18: }
19: }
c.switch语句
1: func main() {
2: finger := 4
3: switch finger {
4: case 1:
5: fmt.Println("Thumb")
6: case 2:
7: fmt.Println("Index")
8: case 3:
9: fmt.Println("Middle")
10: case 4:
11: fmt.Println("Ring")
12: case 5:
13: fmt.Println("Pinky")
14: }
15: }
case语句另一种写法
1: func main() {
2: letter:="i"
3: switch letter {
4: case "a","e","e","o","u"
5: fmt.Println("vowel")
6: default:
7: fmt.Println("not a vowel")
8: }
9: }
switch default
如果所有case条件不满足,那么就会执行default语句
1: func main() {
2: // 变量finger的生命周期在switch内
3: switch finger:=2;finger {
4: case 1:
5: fmt.Println("Thumb")
6: case 2:
7: fmt.Println("Index")
8: case 3:
9: fmt.Println("Middle")
10: case 4:
11: fmt.Println("Ring")
12: case 5:
13: fmt.Println("Pinky")
14: default:
15: fmt.Printf("invaild a=%d ", finger)
16: }
17: }
switch case条件判断
1: func main() {
2: num:=75
3: switch {
4: case num >= 0&& num <=50:
5: fmt.Println("省略...")
6: case num >= 51 && num <= 100:
7: fmt.Println("...")
8: case num >= 101:
9: fmt.Println("...")
10: }
11: }
switch fallthrough执行并穿透到下一个case语句
1: func main() {
2: switch num:= 101;{
3: case num<50:
4: fmt.Printf("<50")
5: fallthrough
6: case num<100:
7: fmt.Printf("<100")
8: fallthrough
9: case num<200:
10: fmt.Printf("<200")
11: }
12: }
乘法表练习:
1: func MultiTable() {
2: for i:=1;i<10;i++ {
3: for j:=1;j<=i;j++ {
4: fmt.Printf(" %d * %d = %d ", j, i, j*i)
5: }
6: fmt.Println()
7: }
8: }