Golang: loop
Go has only one loop construct, the for loop.
package main import "fmt" // example of for loop func main() { // scope of i is within the curly bracket {} for i := 0; i < 4; i++ { fmt.Println(i) } } // 0 // 1 // 2 // 3
Note: no parenthesis after the for
keyword.
Adding parenthesis creates invalid syntax.
Curly brackets {} are always required.
Like While Loop
- The variable init part is optional.
- The variable increment part (called the post statement) is optional.
package main import "fmt" // for loop with just test condition func main() { var ss = 1 for ss <= 3 { fmt.Println(ss) ss++ } } // prints // 1 // 2 // 3
This is the same as C language's “while” statement.
Infinite Loop
package main import "fmt" func main() { uu := 1 // infinite loop, use break to exit for { uu++ fmt.Println(uu) if uu >= 4 { break } } }
break loop
package main import "fmt" func main() { for i := 0; i < 9; i++ { if i == 4 { break } fmt.Println(i) } }
continue loop
package main import "fmt" func main() { for i := 1; i <= 3; i++ { for j := 1; j <= 99; j++ { if j <= 2 { fmt.Println(i, j) } else { continue } } } } // 1 1 // 1 2 // 2 1 // 2 2 // 3 1 // 3 2
Reference
The Go Programming Language Specification - The Go Programming Language#For_statements
The Go Programming Language Specification - The Go Programming Language#Break_statements
The Go Programming Language Specification - The Go Programming Language#Continue_statements
Golang Topics
Patreon me $5. Ask me question on patreon