The use of range in the go language
- 2020-05-27 05:49:16
- OfStack
This article illustrates the use of range in the go language. Share with you for your reference. The specific analysis is as follows:
range is a function defined by the go language system.
The function iterates through each value in an array, returning the lower value of the value and the actual value here.
If a[0]=10, then the return value of a[0] is 0, 10.
Here is an example: this example is the average value of an array.
package main
import (
"fmt"
)
func main() {
sum := 0.0
var avg float64
xs := []float64{1, 2, 3, 4, 5, 6}
switch len(xs) {
case 0:
avg = 0
default:
for _, v := range xs {// The underscore indicates that the value is left out, that is, the subscript index is left out
sum += v
}
avg = sum / float64(len(xs))
}
fmt.Println(avg)
}
I hope this article has been helpful to your programming of Go language.