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.