A range in the Go language
The range keyword in the Go language is used to
- The element of a for loop that iterates over a group (array), slice (slice), linked list (channel), or set (map);
- It returns the index value of the element in the array and in the slice,
- Returns the key value of the Key-value pair in the collection.
Second, the code example
Package Mainimport"FMT"Func Main () {//This is where we use range to ask for 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)//using range on the array will pass in the index and the value of 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 the map's key-value pairs. KVS: = map[string]string{"a":"Apple","b":"Banana"} forK, V: =range KVS {fmt. Printf ("%s\n,%s", 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)} }
If you delete the code on line seventh, the result will change to:
This is because the for _ means traversing the subscript of an array, starting from nums[0],nums[1],nums[2], and then iterating, so the last value is sum=2+3+4=9, but if the for _ is removed, it becomes a traverse 0 1 2, so sum=0+1+2=3.
In this code I represents an array of small, counting from 0, C for the ASCII value corresponding to the character, so traverse the [hello] character array, and get the ASCII value corresponding to the character under the subscript of each array.