WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Go · Basic · question 18 of 100

What is the difference between ’for’ and ’range’ in Go?

📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

In Go language, ‘for‘ and ‘range‘ are not separate control structures; instead, they are parts of a single control structure called a "for loop." The ‘for‘ keyword is used to create loops, while the ‘range‘ keyword allows you to iterate over elements in a collection such as arrays, slices, or maps.

Here, let me explain the difference between using ‘for‘ and ‘for‘ with ‘range‘:

1. ‘for‘ without the ‘range‘ keyword

A regular ‘for‘ loop in Go has the following syntax:

for initialization; condition; post {
    // loop body
}

The loop consists of an initialization step, a condition that needs to be true for the loop to continue, and a post step that gets executed after every iteration. For example, here is a simple for loop that calculates the sum of the numbers from 1 to 5:

package main

import (
    "fmt"
)

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

2. ‘for‘ with the ‘range‘ keyword

On the other hand, when iterating over elements in a collection (such as an array, slice, or map), ‘for‘ with the ‘range‘ keyword is used:

for index, element := range collection {
    // loop body
}

Using the ‘range‘ keyword, we can iterate over elements in the collection and retrieve both the index and the value in the loop. For example, here is a loop that iterates over a slice of numbers and calculates their sum:

package main

import (
    "fmt"
)

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    sum := 0
    for _, num := range numbers {
        sum += num
    }
    fmt.Println("Sum:", sum)
}

In this case, we are not interested in the index of each element, so we use the underscore ‘_‘ as a placeholder.

To summarize, the ‘for‘ keyword is the primary looping mechanism in Go, while the ‘range‘ keyword extends its functionality to make it easy to iterate over elements in collections like arrays, slices, and maps.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Go interview — then scores it.
📞 Practice Go — free 15 min
📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

All 100 Go questions · All topics