这是本Golang系列教程的第九篇。

循环语句用于重复执行一段代码。

forwhiledo while
for 语句语法

for 语句的语法如下:

for initialisation; condition; post {  
}
initialisationinitialisationconditionconditiontrue{}postconditionfalsepostpostconditiontrue
forinitialisationconditionpostfor
例子
for110
package main

import (  
    "fmt"
)

func main() {  
    for i := 1; i <= 10; i++ {
        fmt.Printf(" %d",i)
    }
}
i1i10iposti1i10
1 2 3 4 5 6 7 8 9 10
forforifor
break
breakforfor
15break
package main

import (  
    "fmt"
)

func main() {  
    for i := 1; i <= 10; i++ {
        if i > 5 {
            break //loop is terminated if i > 5
        }
        fmt.Printf("%d ", i)
    }
    fmt.Printf("\nline after for loop")
}
ii5breakforfmt.Printf
1 2 3 4 5  
line after for loop  
continue
continueforcontinue
continue110
package main

import (  
    "fmt"
)

func main() {  
    for i := 1; i <= 10; i++ {
        if i%2 == 0 {
            continue
        }
        fmt.Printf("%d ", i)
    }
}
if i%2 == 0i200icontinuecontinuefmt.Printf1 3 5 7 9
更多例子
for
010
package main

import (  
    "fmt"
)

func main() {  
    i := 0
    for ;i <= 10; { // initialisation and post are omitted
        fmt.Printf("%d ", i)
        i += 2
    }
}
forinitialisationconditionpostinitialisationpostifor0i <= 10i20 2 4 6 8 10
;forwhile
package main

import (  
    "fmt"
)

func main() {  
    i := 0
    for i <= 10 { //semicolons are ommitted and only condition is present
        fmt.Printf("%d ", i)
        i += 2
    }
}
for
package main

import (  
    "fmt"
)

func main() {  
    for no, i := 10, 1; i <= 10 && no <= 19; i, no = i+1, no+1 { //multiple initialisation and increment
        fmt.Printf("%d * %d = %d\n", no, i, no*i)
    }

}
noi1011condition&&i10no19
10 * 1 = 10  
11 * 2 = 22  
12 * 3 = 36  
13 * 4 = 52  
14 * 5 = 70  
15 * 6 = 90  
16 * 7 = 112  
17 * 8 = 136  
18 * 9 = 162  
19 * 10 = 190  
无限循环

可以用下面的语法实现无限循环:

for {  
}
Hello World
package main

import "fmt"

func main() {  
    for {
        fmt.Println("Hello World")
    }
}
process took too long"Hello World"

还有一个 range for 可用于遍历数组,我们将在介绍数组时介绍它。


循环语句的介绍到此结束。感谢阅读。