This is a creation in Article, where the information may have evolved or changed.
Go language Range (range)
The range keyword in the Go language is used for elements of an array, slice (slice), linked list (channel), or collection (map) in a for loop. It returns the index value of the element in the array and the slice, and returns the key value of the Key-value pair in the collection.
Instance
PackageMainImport "FMT"Func main() { //This is where we use range to find a slice and. Using arrays is similar to thisNums:= []int{2, 3, 4}sum:= 0 for _,Num:=Range Nums{sum+=Num}FMT.Println("sum:",sum) //Use range on the array to pass in index and value two variables. In the above example, we don't need to use the ordinal of the element, so we omit it with the whitespace character "_". Sometimes we really need to know its index. forI,Num:=Range Nums{ ifNum== 3 {FMT.Println("Index:",I) } } //range can also be used on map key-value pairs. KVS:=Map[string]string{"a": "Apple", "B": "Banana"} fork,v:=Range KVS{FMT.Printf("%s-%s\n",k,v) } //range can also be used to enumerate Unicode strings. The first argument is the index of the character, and the second is the character (the Unicode value) itself. forI,C:=Range"Go" {FMT.Println(I,C) }}
The above example runs the output as:
sum: 9Index: 1a -Appleb -Banana0 1031 111