這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。Go by Example: For
for is Go’s only looping construct. Here are three basic types of for loops.
The most basic type, with a single condition.
A classic initial/condition/after for loop.
for without a condition will loop repeatedly until you break out of the loop or return from the enclosing function.
package mainimport "fmt"func main() { i := 1 for i <= 3 { fmt.Println(i) i = i + 1 } for j := 7; j <= 9; j++ { fmt.Println(j) } for { fmt.Println("loop") break }}
譯:
for 關鍵字是在go語言中唯一一個迴圈結構,下面的就是for迴圈的三個基本類型結構
最基本的是一個單條件
一個是 初始值/條件/然後的自身處理條件對於 for迴圈
for 迴圈對於沒有條件的將會一直迴圈直到break出迴圈,或者在外圍函數返回
package mainimport "fmt"func main() {i := 1for i <= 3 { //相當於while迴圈fmt.Println(i)i = i + 1}for j := 7; j <= 10; j++ { //傳統的for迴圈fmt.Println(j)}for { //類似於 do。。。while迴圈fmt.Println("loop")break}}
運行結果
go run for.go
1
2
3
7
8
9
10
loop
原文地址