流程控制之-条件语句

判断语句 if

if判断示例:

1
2
3
//初始化与判断写在一起: if a := 10; a == 10
if i == '3' {
}

if的特殊写法:

1
2
if err := Connect(); err != nil {         // 这里的 err!=nil 才是真正的if判断表达式
}

分支语句 switch

示例:

1
2
3
4
5
6
7
8
switch num {
case 1: // case 中可以是表达式
fmt.Println("111")
case 2:
fmt.Println("222")
default:
fmt.Println("000")
}

贴士: - Go保留了break,用来跳出switch语句,上述案例的分支中默认就书写了该关键字 - Go也提供fallthrough,代表不跳出switch,后面的语句无条件执行

流程控制之-循环语句

for循环

Go只支持for一种循环语句,但是可以对应很多场景:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//传统的for循环
for init,condition;post{
}

//for循环简化
var i int
for ; ; i++ {
if(i > 10){
break;
}
}

//类似while循环
for condition {}

//死循环
for{
}

//for range:一般用于遍历数组、切片、字符串、map、管道
for k, v := range []int{1,2,3} {
}

跳出循环

常用的跳出循环关键字: - break用于函数内跳出当前forswitchselect语句的执行 - continue用于跳出for循环的本次迭代。
- goto可以退出多层循环

break跳出循环案例(continue同下):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
OuterLoop:
for i := 0; i < 2; i++ {
for j := 0; j < 5; j++ {
switch j {
case 2:
fmt.Println(i,j)
break OuterLopp
case 3:
fmt.Println(i,j)
break OuterLopp
}
}
}

goto跳出多重循环案例:

1
2
3
4
5
6
7
8
9
10
11
12
for x:=0; x<10; x++ {

for y:=0; y<10; x++ {

if y==2 {
goto breakHere
}
}

}
breakHere:
fmt.Println("break")

贴士:goto也可以用来统一错误处理。

1
2
3
4
5
6
if err != nil {
goto onExit
}
onExit:
fmt.Pritln(err)
exitProcess()

流程控制之-条件语句

https://hunlp.com/posts/36713.html

作者

ฅ´ω`ฅ

发布于

2021-06-10

更新于

2021-06-10

许可协议


评论