Skip to main content
Published on

For Loop in Go

Share:

Introduction

The for loop is one of the most fundamental control structures in any programming language. In Go, it offers flexibility and power that adapt to a wide variety of situations.

Basic Components of the for Loop

The for loop in Go can be seen in three main variations:

  1. Counter-based: As in many other languages, you can define an initialisation, condition, and post-processing step.
  2. Condition-based: Here, only a condition is specified. Similar to a while in other languages.
  3. Range: This variation allows iterating over slices, arrays, and other iterable data types.

Examples

// Counter-Based
for i := 0; i < 10; i++ {
  fmt.Println(i)
}

// Condition-Based
j := 0

for j < 10 {
  fmt.Println(j)
  j++
}

// Range
fruits := []string{"Apple", "Banana", "Cherry"}

for index, fruit := range fruits {
  fmt.Printf("fruits[%d]: %s\n", index, fruit)
}

Watch Out for Infinite Loops

As mentioned, it is vital to be aware of the possibility of creating infinite loops. Always check the conditions of your loop and make sure there is an exit.

// An example of an infinite loop. Do not run this code!

/*
for {
  fmt.Println("This is an infinite loop!")
}
*/

Advanced Variations

It is possible to combine the variations of the for loop in creative ways to meet different needs. For example, you can use a condition-based variation to traverse slices, based on specific business logic.

fruits := []string{"Apple", "Banana", "Cherry"}
index := 0

for index < len(fruits) {
  fmt.Println(fruits[index])
  index += 2 // Skip every two fruits
}

Conclusion

The for loop is a versatile and essential tool in the arsenal of any Go programmer. Whether you are performing simple tasks or implementing complex algorithms, the ability to control the flow of execution is invaluable.

Happy coding!