Sling Academy
Home/Golang/Using For loop in Go (from basic to advanced)

Using For loop in Go (from basic to advanced)

Last updated: November 23, 2024

The for loop in Go is a fundamental control structure that allows you to execute a block of code repeatedly. It's highly versatile and ubiquitous in most Go programs. We'll explore its use from basic scenarios to more advanced implementations.

Basic Usage of For Loop

The syntax of a basic for loop in Go is simple. Here's a straightforward example:

package main

import "fmt"

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

In this example, the loop will print the numbers 0 through 4. The loop contains three main components: initialization (i := 0), condition (i < 5), and post-expression (i++).

Intermediate Usage: Loop without Condition

The for loop can also be used without any condition, functioning as an infinite loop if not terminated by any internal logic. Consider this example:

package main

import "fmt"

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

Here, the loop will continue indefinitely until it hits the break statement when i equals 5.

Advanced Usage: Nested Loops and Ranges

Nested loops are another powerful use of the for loop. They allow you to perform complex tasks, such as iterating over multi-dimensional data structures:

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)
        }
    }
}

This code will print pairs of (i, j) from (1, 1) to (3, 3).

Go also provides a convenient way to loop over slices, arrays, maps, or channels using the range keyword:

package main

import "fmt"

func main() {
    numbers := []int{10, 20, 30, 40}
    for index, value := range numbers {
        fmt.Printf("Index: %d, Value: %d\n", index, value)
    }
}

Each iteration of the loop gives you the index and value of an element of the slice numbers.

Conclusion

The for loop is a versatile tool in Go that covers all the looping needs through its different forms. From simple loops to nested loops and iteration over collections, Go's for loop keeps your code efficient and clear.

Next Article: If, Else, and Beyond: Go's Conditional Statements

Previous Article: Grouped and shorthand declaration in Go

Series: Variables & Control Flow

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant