Control Flow
For Each in Go
The for-each loop iterates through every element in an array, slice, string, or map without specifying the length. It uses the range keyword.
Syntax
for key, value := range collection {
//the individual keys and values are held in the iterator variable
//key or value can be dropped if one or the other is not needed using '_'
}
Notes
Each element is assigned temporary iterator variables, declared in the for-each structure.
For any associative data structure, to get only values, use 'for _, value'. To get only keys, use 'for key'.
Order is not necessarily guaranteed in a for each iteration.
Example
studentGrades := [3]int{50, 89, 75}
for _, grade := range studentGrades {
fmt.Println("Grade: ", grade)
} //prints each value of the array studentGrades (each loop is an element of studentGrades assigned to grade variable).