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, it acts like “while loop” in other langs. Example:

for x < 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.

Here's example for array or slice:

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

If one of the variable you don't need, name it _, else compiler will complain. The _ is called “blank identifier”.

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

Here's example for map:

for key, value := range map { fmt.Println(key, val) }

[see Golang: Array]

[see Golang: Slice]

[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. Pointer
  22. String as Chars
  23. regexp
  24. Read File
  25. Write to File
  26. Walk Dir
  27. Check File Exist
  28. System Call
  29. Get Script Path
  30. Pointer
  31. Defer
  32. Random Number

Examples

  1. Match Any Regexp
  2. Find Replace
  3. Validate Links
  4. Generate Sitemap

Reference

  1. Go Spec