search

What is the difference between Go's for loop and range loop?

Go's for loop and range loop are both used for iterating over data structures, but they have different use cases.

The **for** loop in Go is a traditional loop that allows you to specify an initialization statement, a condition statement, and a post-statement. It is often used for iterating over a sequence of numbers or for running a block of code a certain number of times. Here's an example:

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

The above code will print the numbers from 0 to 9.

The **range** loop in Go is used for iterating over data structures such as arrays, slices, maps, or strings. It returns both the index and the value of each element in the data structure. Here's an example:

numbers := []int{1, 2, 3, 4, 5}

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

The above code will print the index and value of each element in the **numbers** slice.

In summary, the **for** loop is used for iterating a fixed number of times, while the **range** loop is used for iterating over data structures.

Related Questions You Might Be Interested