循环结构的语法如下
gofor init; condition; post {
    //循环体代码块
}
for表明接下来的代码是for循环结构;init是初始化语句;condition是关系或逻辑表达式,值为false时则会停止循环;post是每次循环结束后执行的语句;循环体代码块就是要重复执行的代码了。相关信息
go// 终止本次循环,执行下一个循环
continue
    
// 终止整个循环
break
举例说明:
gon := 7
for i := 1; i <= n; i++ {
    for j := 0; j < n-i; j++ {
       fmt.Print(" ")
    }
    for k := 0; k < 2*i-1; k++ {
       fmt.Print("*")
    }
    fmt.Println()
}
Init 和 post 语句是可选的,因此我们也可以使我们的for循环表现得像一个 while 循环
goi := 0
for ;i < 10; {
    i += 1
}
go// 死循环
for {
    // do something
}
条件分支结构语法如下
condition是关系或逻辑表达式
goif condition {
    //条件成立时要执行的语句
}else{
    //条件不成立时要执行的语句
}
go// 如无必要,else是可以省略的
if condition {
    //条件成立时要执行的语句
}
go// 如有必要,还可追加更多的判断条件
if condition1 {
    //条件condition1成立时要执行的语句
}else if condition2 {
    //条件condition2成立时要执行的语句
}else if condition3 {
    //条件condition3成立时要执行的语句
}else{
    //以上三种条件都不成立时要执行的语句
}
举例说明:
govar a int = 10
var b int = 5
var c int = 20
if a > b || a > c {
    fmt.Print("ok")
}
switch 的本质是:将 case 与 condition 判等,若为 true 则执行
相关信息
在 Go 中,switch case 只运行第一个值等于条件表达式的 case,而不是后面的所有 case。
因此,与其他语言不同,break语句会自动添加到每个案例的末尾。
gofunc main() {
    day := "monday"
    switch day {
    case "monday":
	fmt.Println("time to work!")
    case "friday":
	fmt.Println("let's party")
    default:
	fmt.Println("browse memes")
    }
}
// time to work
如果需要执行其他 case,则需要使用 fallthrough 关键字来进行
goswitch day := "monday"; day {
case "monday":
    fmt.Println("time to work!")
    //这里使用了 fallthrough
    fallthrough
case "friday":
    fmt.Println("let's party")
default:
    fmt.Println("browse memes")
}
// time to work!
// let's party
注意
如果不填入条件,默认为 switch true
gox := 10
switch {
    case x > 5:
        fmt.Println("yes")
    default:
	fmt.Println("no")
}
// yes
gox := 1
switch {
    case x > 5:
        fmt.Println("yes")
    default:
	fmt.Println("no")
}
// no
goto 可以跳转到程序中指定的行
和嵌套循环里的break标签是一样的,不管后面还有多少代码都不再执行。
goTestLabel: 
for a := 20; a < 35; a++ {
    if a == 25 {
        a += 1
        goto TestLabel
    }
    fmt.Println(a)
    a++
}
本文作者:Silon汐冷
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!