跳到主要内容

流程控制

一 流程控制之-条件语句

1.1 判断语句 if

if判断示例:

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

if的特殊写法:

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

1.2 分支语句 switch

示例:

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

贴士:

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

二 流程控制之-循环语句

2.1 for循环

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

// 传统的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} {
}

2.2 跳出循环

常用的跳出循环关键字:

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

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

OuterLoop:
for i := 0; i < 2; i++ {
for j := 0; j < 5; j++ {
switch j {
case 2:
fmt.Println(i,j)
break OuterLoop
case 3:
fmt.Println(i,j)
break OuterLoop
}
}
}

goto跳出多重循环案例:

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

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

if y==2 {
goto breakHere
}
}

}
breakHere:
fmt.Println("break")

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

if err != nil {
goto onExit
}
onExit:
fmt.Pritln(err)
exitProcess()