go流程控制结构

go语言学习-(流程控制语句:for、if、else、switch、defer)

for

Go只有一种循环结构: for循环
Go的for语句后面没有小括号()大括号{}是必须的
初始化语句和后置语句是可选的

1
2
3
4
5
6
7
8
9
for a=0;a<10;a++{

}

for ;a<10; {
}
//上面可以去掉;就等于c语言中的while
for a<10 {
}

if

if语句与for循环类似,表达式外无需小括号(),而大括号{}则是必须的。
if语句可以在表达式前执行一个简单的语句。
该语句申明的变量作用域仅在if之内

1
2
3
4
5
6
if a<10 {
}

if b := 10;b<10{

}

switch

go自动提供了在这些语言中的每个case后面所需的break语句。
go的另一个重点的不同在于switch的case 无需为常量,且取值不必为整数。

1
2
3
4
5
6
7
8
9
10
11
os := runtime.GOOS
switch os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
// freebsd, openbsd,
// plan9, windows...
fmt.Printf("%s.", os)
}

无条件的switch == switch true

1
2
3
4
5
6
7
8
switch {
case 1:
fmt.Printf('1')
case 2:
fmt.Printf('2')
default:
fmt.Printf('default')
}

defer

defer 语句会将函数推迟到外层函数返回之后执行

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

import "fmt"

func main() {
defer fmt.Println("world")

fmt.Println("hello")

fmt.Println("hello111")
}

//程序返回
hello
hello111
world

defer 栈

推迟的函数调用会被压入一个栈中。当外层函数返回时,被推迟的函数会按照后进先出的顺序调用。

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

import "fmt"

func main() {
fmt.Println("counting")

for i := 0; i < 10; i++ {
defer fmt.Println(i)
}

fmt.Println("done")
}
//返回
counting
done
9
8
7
6
5
4
3
2
1
0