Loop Init, Condition, Post

Part of Golang Mastery course

~15 min read
Interactive
Hands-on
Beginner-friendly

As you're learning Go, a good quick reference is Go by Example.

For example, here's what it has for for

example.go
package main
 
import string">"fmt"
 
func main() {
 
i := 1
for i <= 3 {
fmt.Println(i)
i = i + 1
}
 
for j := 7; j <= 9; j++ {
fmt.Println(j)
}
 
for n := 0; n <= 5; n++ {
if n%2 == 0 {
continue
}
fmt.Println(n)
}
}
 

Note: There is no while in Go.

The way to create a loop is to start with for, and the first thing you put in is an init statement, a condition, and a post, e.g.

example.go
for init; condition; post {
}
 

Let's try a loop with an init statment initializing a variable i with the value 0, the condition that i is less than or equal to 100, and the post of incrementing i by 1 (i++). Remember, we can always check the Go spec. In this case, IncDec statements has information explaining the ++ and -- operators.

example.go
package main
 
import (
string">"fmt"
)
 
func main() {
string">"comment">// for init; condition; post {}
for i := 0; i <= 100; i++ {
fmt.Println(i)
}
}
 

playground

Your Progress

13 of 103 modules
13%
Started13% Complete
Previous
SpaceComplete
Next