Use range to traverse elements in a variety of data structures. Let's see how to use range to traverse some of the data structures we've already learned.
Package Mainimport "FMT" Func Main () {// here we use range traversal slice to sum //This method is also applicable to the array. nums: = []int{2, 3, 4} sum: = 0 for _, num: = range nums { sum + = num } fmt. Println ("sum:", sum) //range is used to iterate through arrays and slices, returning index and element value (value). If we don't care, the index can use a null-value definition (_) to ignore this return value //And we sometimes need this index. for i, num: = Range nums { if num = = 3 { FMT. Println ("Index:", i) } } //When using range to traverse the dictionary, return the key-value pair (key/value). KVS: = map[string]string{"A": "Apple", "B": "Banana"} for K, V: = range KVS { fmt. Printf ("%s-%s\n", K, V) } //The range function is used to iterate through a string, returning a Unicode code point. The first return value is the index of the starting byte of each character, and the second 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.
English original
Go by Example:range