There are no generics in Go, so you cannot write a solution that covers []int and []float64 at the same time. You must copy the values ββfrom []int to []float64 with a simple conversion for the loop and type from int to float . Then you can use your function. Example ( play ):
a := []int{1,2,3,4} b := make([]float64, len(a)) for i := range a { b[i] = float64(a[i]) } StdDev(b)
What you can also do is write a function based on reflection values ββand then use reflect.MakeFunc . It will be slower, harder to do and write more code, so the advantage will be dubious.
Code Style
Although this is off topic, I cannot help but notice that your code may look better if you use a range of sentences for your loops. In addition, variables in the function body are written in the lower caps. There are other syntax tricks, such as named return values. Using these Go features, your code might look better:
func Avg(a []float64) (sum float64) { for i := range a { sum += a[i] } return sum / float64(len(a)) } func StdDev(a []float64) (total float64) { prom := Avg(a) for i := range a { total += (a[i] - prom) * (a[i] - prom) } total = total / float64(len(a)) return math.Sqrt(total) }
source share