Golang: loop

By Xah Lee. Date: . Last updated: .

Go has only one loop construct, the for loop.

for loop can:

Loop a Fixed Number Times

for i := 0; i < 4; i++ { … }

package main

import "fmt"

func main() {
    // scope of i is the whole for statement
    for i := 0; i < 4; i++ {
        fmt.Printf("%v ", 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

for loop with just test condition, acts like “while loop” in other langs. e.g.

for ss < 3 {…}

package main

import "fmt"

func main() {
    var ss = 1

    // for loop with just test condition
    // this acts like “while loop” in other langs
    for ss <= 3 {
        fmt.Printf("%v ", ss)
        ss++
    }
}

// 1 2 3

Infinite Loop

for {…}

If no condition is used, loop acts like a infinite loop.

You break the loop using keyword break.

package main

import "fmt"

func main() {
    var uu = 1

    // infinite loop
    for {
        fmt.Printf("%v ", uu)
        uu++

        // use break to exit
        if uu > 4 {
            break
        }
    }
}

// 1 2 3 4

break loop

The keyword break lets you break a loop. Useful when you want to exit the loop when some condition is met.

package main

import "fmt"

func main() {

    for i := 0; i < 9; i++ {
        fmt.Printf("%v ", i)
        if i == 4 {
            break
        }
    }
}

// 0 1 2 3 4

continue loop

The keyword continue lets you exit the inner loop of a nested 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

For Range Loop

for loop has a second syntax, with range. It lets you loop over array, slice, string, map.

for i, x := range array { fmt.Println(i, x) }

If one of the variable you don't need, name it _, else compiler will complain.

for _, x := range array { fmt.Println(x) }

The _ is called “blank identifier”.

Loop Thru Array or Slice

package main

import "fmt"

func main() {
    var arr = []string{"aa", "bb", "cc"}
    for i, x := range arr {
    fmt.Println(i, x)
    }
    // prints
    // 0 aa
    // 1 bb
    // 2 cc

}

[see Golang: Array]

[see Golang: Slice]

Loop Thru Map

package main

import "fmt"

func main() {

    var mm = map[string]int{"a": 1, "b": 2}

    for kk, vv := range mm {
        fmt.Printf("%v, %v\n", kk, vv)
    }
    // prints
    // a, 1
    // b, 2

}

[see Golang: Map]

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

If you have a question, put $5 at patreon and message me.

Golang

  1. Compile, Run
  2. Package, Import
  3. Comment
  4. Print
  5. String
  6. Rune
  7. Variable
  8. Zero Value
  9. Constant
  10. If Then Else
  11. Switch/Case
  12. Loop
  13. Basic Types
  14. Array
  15. Slice
  16. Map
  17. Struct
  18. Function
  19. regexp
  20. Read File
  21. Write to File
  22. Walk Dir
  23. Check File Exist
  24. System Call
  25. Get Script Path
  26. Pointer
  27. Defer
  28. Random Number

Examples

  1. match any regexp
  2. Validate Links
  3. Generate Sitemap

Reference

  1. Go Spec