Go has a few for loop options:
- Classic for:
for i := 0; i < 5; i++
- for using range:
for index, element := range listOfThings
- for as a
while
loop:for done != true
Classic for loop
This format is common in many languages:
func main() {
for i := 0; i < 3; i++ {
fmt.Printf("Hi %d\n", i)
}
}
main()
// Hi 0
// Hi 1
// Hi 2
The one difference in Go is the lack of opening parentheses around the init statements1, which are required in other languages like Javascript, Java, or C.
For loop using range
Golang doesn’t have a for in
loop, but range
acts similarly:
func main() {
letterSlice := []string{"a", "b", "c"}
for index, letter := range letterSlice {
fmt.Printf("Index: %d, Letter: %s\n", index, letter)
}
}
main()
// Index: 0, Letter: a
// Index: 1, Letter: b
// Index: 2, Letter: c
For loop as a while loop
Many languages have a for
loop and a separate while
loop—Go does not.
func main() {
complete := false
for != complete {
// this will loop until you set complete = true inside the loop
}
}
Break and continue statements
These work as expected with any of Go’s loop formats.
Continue skips to the next loop iteration:
func main() {
for i := 0; i < 3; i++ {
if i == 1 {
fmt.Println("i == 1, skipping")
continue
}
fmt.Printf("Hi %d\n", i)
}
}
main()
// Hi 0
// i == 1, skipping
// Hi 2
Break exits the loop:
func main() {
letterSlice := []string{"a", "b", "c"}
for index, letter := range letterSlice {
if letter == "c" {
fmt.Printf("found c, exiting loop")
break
}
fmt.Printf("Index: %d, Letter: %s\n", index, letter)
}
}
main()
// Index: 0, Letter: a
// Index: 1, Letter: b
// found c, exiting loop
If you have nested loops break
and continue
will only affect the innermost loop, but that’s common across all languages, not just Go.
- Technically it’s the init, condition, and post statements ↩︎