Introduction to for Loops in Go Programming

Introduction to for Loops

Are you ready to level up your Go programming skills? We are moving into more advanced techniques to take full control of Go's capabilities. This lesson focuses on the for loop — a versatile and powerful tool in Go that will enhance your coding efficiency tremendously.

Exploring for Loops

In Go, a for loop allows us to execute a block of code a certain number of times or over a collection. It's incredibly useful for handling repetitive tasks without manually programming each repetition.

Classic "for" Loop Syntax

The traditional syntax for a for loop in Go consists of three components: initialization, condition, and increment. This is typically used when you know in advance how many times you'd like the loop to run. Here's an example:

package main

import "fmt"

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

In this example:

  • Initialization: i := 0 sets up a loop variable i starting at 0.
  • Condition: i < 5 continues the loop as long as i is less than 5.
  • Increment: i++ increases i by 1 after each iteration.

Running this loop, you'd see:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4

This structure provides a clear and controlled way to run code a specified number of times.

Using for Loops with Collections

For loops become even more powerful when combined with Go's capability to iterate over collections. For example, consider visiting each country in a list for a trip. Let's see what it looks like in Go:

package main

import "fmt"

func main() {
    tripCountries := []string{"France", "Italy", "Spain", "Japan"}

    for _, country := range tripCountries {
        fmt.Println("Considering", country, "for the trip.")
    }
}

In this scenario, the loop iterates over tripCountries, with range used to specify the collection to iterate over. The loop assigns each element to the variable country during each iteration and executes the block of code with fmt.Println.

Running the loop, you would see:

Considering France for the trip.
Considering Italy for the trip.
Considering Spain for the trip.
Considering Japan for the trip.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal