Go by Example: Range, gobyexamplerange
UseRangeIt can traverse elements in various data structures. Let's see how to useRangeTraverse data structures that we have learned.
Package mainimport "fmt" func main () {// here we use range traversal slice to sum // This method also applies to arrays. Nums: = [] int {2, 3, 4} sum: = 0 for _, num: = range nums {sum + = num} fmt. println ("sum:", sum) // when range is used to traverse arrays and slices, index and element value are returned ). // if you do not care about the index, you can use a null value operator (_) to ignore this return value. // Of course, we also need this index sometimes. For I, num: = range nums {if num = 3 {fmt. println ("index:", I) }// when range is used to traverse the dictionary, the key-value Pair (key/value) is returned ). Kvs: = map [string] string {"a": "apple", "B": "banana"} for k, v: = range kvs {fmt. printf ("% s-> % s \ n", k, v)} // The Unicode code point is returned when the range function is used to traverse strings. // The first return value is the index of the starting byte of each character, and the second value is the rune character. For I, c: = range "go" {fmt. Println (I, c )}}
Output
$ go run range.go sum: 9index: 1a -> appleb -> banana0 1031 111
Next Example: Go by Example: Functions.
Original ENGLISH