January 2018
Intermediate to advanced
340 pages
8h 6m
English
The range keyword is used to iterate over a slice, map, or other data structure. The range keyword is used in combination with the for loop, to operate on an iterable data structure. The range keyword returns the key and value variables. Here are some basic examples of using the range keyword:
package mainimport "fmt"func main() { intSlice := []int{2, 4, 6, 8} for key, value := range intSlice { fmt.Println(key, value) } myMap := map[string]string{ "d": "Donut", "o": "Operator", } // Iterate over a map for key, value := range myMap { fmt.Println(key, value) } // Iterate but only utilize keys for key := range myMap { fmt.Println(key) } // Use underscore to ignore keys for _, value := range myMap { fmt.Println(value) }}
Read now
Unlock full access