In Go, iteration is a fundamental concept that allows you to loop over data structures such as arrays, slices, maps, and channels. While Go does not have a traditional foreach loop like some other languages, it provides a powerful alternative using the range keyword with for loops.
Introduction to Range
The range keyword is used in conjunction with for loops to iterate over data structures. It returns two values: an index and a value. The index represents the current position in the data structure, and the value is a copy of the element at that index.
Iterating Over Arrays and Slices
To iterate over an array or slice, you can use the following syntax:
arr := [3]int{1, 2, 3}
for i, v := range arr {
fmt.Println(i, v)
}
This will output:
0 1
1 2
2 3
If you don’t need the index, you can use the blank identifier _ to ignore it:
arr := [3]int{1, 2, 3}
for _, v := range arr {
fmt.Println(v)
}
This will output:
1
2
3
Iterating Over Maps
To iterate over a map, you can use the following syntax:
m := map[string]int{"a": 1, "b": 2, "c": 3}
for k, v := range m {
fmt.Println(k, v)
}
This will output:
a 1
b 2
c 3
Note that the order of iteration is not guaranteed for maps.
Iterating Over Channels
To iterate over a channel, you can use the following syntax:
ch := make(chan int)
for v := range ch {
fmt.Println(v)
}
This will receive values from the channel until it is closed.
Best Practices
- Use
rangewithforloops to iterate over data structures. - Use the blank identifier
_to ignore indices or values when not needed. - Be aware of the order of iteration for maps, which is not guaranteed.
Example Code
Here’s an example code that demonstrates iteration over arrays, slices, and maps:
package main
import "fmt"
func main() {
arr := [3]int{1, 2, 3}
fmt.Println("Array:")
for i, v := range arr {
fmt.Printf("%d: %d\n", i, v)
}
slice := []int{4, 5, 6}
fmt.Println("Slice:")
for _, v := range slice {
fmt.Println(v)
}
m := map[string]int{"a": 1, "b": 2, "c": 3}
fmt.Println("Map:")
for k, v := range m {
fmt.Printf("%s: %d\n", k, v)
}
}
This code will output:
Array:
0: 1
1: 2
2: 3
Slice:
4
5
6
Map:
a: 1
b: 2
c: 3
In conclusion, Go’s range keyword provides a powerful way to iterate over data structures using for loops. By following best practices and understanding the syntax, you can write efficient and readable code.