range

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)   }} 

Get Security with Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.