Understanding Loops in Go

3 min read .

Loops are a fundamental concept in programming, allowing you to repeat a block of code multiple times. In Go, the loop structure is simple yet powerful, providing the flexibility to handle various repetitive tasks with ease. Whether you’re iterating over arrays, slices, maps, or channels, Go’s loop constructs have you covered.

The for Loop: Go’s Only Loop

Unlike many other programming languages, Go has only one loop construct: the for loop. This single loop type can be used in different ways to achieve various looping behaviors.

1. Basic for Loop

The basic for loop in Go is similar to the for loop in languages like C, Java, or JavaScript.

package main

import "fmt"

func main() {
    // Basic for loop
    for i := 0; i < 5; i++ {
        fmt.Println(i)
    }
}

Explanation:

  • The loop starts with i set to 0.
  • The loop continues to run as long as the condition i < 5 is true.
  • After each iteration, i is incremented by 1.

2. for Loop as a while Loop

In Go, you can omit the initialization and post statements to create a loop that behaves like a while loop.

package main

import "fmt"

func main() {
    i := 0
    for i < 5 {
        fmt.Println(i)
        i++
    }
}

Explanation:

  • This loop starts with i set to 0.
  • It continues as long as i < 5 is true.
  • After each iteration, i is incremented by 1.

3. Infinite Loop

An infinite loop in Go is created by omitting all three components of the for loop.

package main

import "fmt"

func main() {
    i := 0
    for {
        fmt.Println(i)
        i++
        if i >= 5 {
            break
        }
    }
}

Explanation:

  • The loop runs indefinitely because there’s no condition to stop it.
  • The break statement is used to exit the loop when i reaches 5.

4. Looping Over Collections

Go’s for loop is particularly versatile when it comes to iterating over collections such as arrays, slices, maps, and strings.

Looping Over Arrays and Slices
package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3, 4, 5}

    for index, value := range numbers {
        fmt.Printf("Index: %d, Value: %d\n", index, value)
    }
}

Explanation:

  • The range keyword is used to iterate over each element in the slice.
  • index is the position of the element, and value is the element itself.
Looping Over Maps

When iterating over maps, range returns both the key and value.

package main

import "fmt"

func main() {
    people := map[string]int{"Alice": 30, "Bob": 25, "Charlie": 35}

    for key, value := range people {
        fmt.Printf("Key: %s, Value: %d\n", key, value)
    }
}

Explanation:

  • The range keyword is used to iterate over each key-value pair in the map.
  • key is the map’s key, and value is the corresponding value.
Looping Over Strings

You can also loop over strings, where range returns both the index and the Unicode code point of each character.

package main

import "fmt"

func main() {
    message := "Hello"

    for index, char := range message {
        fmt.Printf("Index: %d, Character: %c\n", index, char)
    }
}

Explanation:

  • The range keyword is used to iterate over each character in the string.
  • index is the position of the character, and char is the Unicode code point.

5. Nested Loops

Go also supports nested loops, where you can place one loop inside another.

package main

import "fmt"

func main() {
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 3; j++ {
            fmt.Printf("i = %d, j = %d\n", i, j)
        }
    }
}

Explanation:

  • The outer loop runs from i = 1 to i = 3.
  • For each iteration of the outer loop, the inner loop runs from j = 1 to j = 3.

Loop Control Statements

Go provides several control statements that you can use within loops:

  • break: Exits the loop immediately.
  • continue: Skips the remaining code in the current iteration and moves to the next iteration.
  • goto: Jumps to a labeled statement.

Here’s an example of using continue and break:

package main

import "fmt"

func main() {
    for i := 0; i < 10; i++ {
        if i%2 == 0 {
            continue // Skip even numbers
        }
        if i > 7 {
            break // Exit loop if i is greater than 7
        }
        fmt.Println(i)
    }
}

Conclusion

Loops are an essential part of any programming language, and Go’s for loop provides all the functionality you need to handle a wide range of tasks. Whether you’re iterating over arrays, slices, maps, or simply repeating code, the for loop in Go is both powerful and easy to use.

Tags:
Golang

See Also

chevron-up