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. Source Encoding
  3. Package, Import
  4. Comment
  5. Print
  6. String
  7. String Backslash Escape
  8. Rune
  9. Variable
  10. Zero Value
  11. Constant
  12. If Then Else
  13. Switch/Case
  14. Loop
  15. Basic Types
  16. Array
  17. Slice
  18. Map
  19. Struct
  20. Function
  21. String as Chars
  22. regexp
  23. Read File
  24. Write to File
  25. Walk Dir
  26. Check File Exist
  27. System Call
  28. Get Script Path
  29. Pointer
  30. Defer
  31. Random Number

Examples

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

Reference

  1. Go Spec