流程控制之-条件语句
判断语句 if
if
判断示例: 1
2
3//初始化与判断写在一起: if a := 10; a == 10
if i == '3' {
}
if
的特殊写法: 1
2if err := Connect(); err != nil { // 这里的 err!=nil 才是真正的if判断表达式
}
分支语句 switch
示例: 1
2
3
4
5
6
7
8switch 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 | //传统的for循环 |
跳出循环
常用的跳出循环关键字: - break
用于函数内跳出当前for
、switch
、select
语句的执行 - continue
用于跳出for
循环的本次迭代。
- goto
可以退出多层循环
break跳出循环案例(continue同下): 1
2
3
4
5
6
7
8
9
10
11
12
13
14OuterLoop:
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
12for 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
6if err != nil {
goto onExit
}
onExit:
fmt.Pritln(err)
exitProcess()
流程控制之-条件语句