So I'm trying to compile the forllowing code in go, which I just picked up a few hours ago
package main
import "fmt"
func main() {
a := [...]float64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
sum := avg(a)
fmt.Println(sum)
}
func avg(arr []float64) (sum float64) {
for _, v := range arr {
sum += v
}
sum = sum / float64(len(arr))
return
}
I get an error saying that I can't pass the 10 element long array because the function was defined with a []float64 array. Is there a way around this or am I missing something obvious?
You define a
as array of length and in avg
you expect a slice of float64
If you dont need fixed length define a
as slice:
a := []float64{...}
Or you can convert array
to slice:
sum := avg(a[:])
You are mixing arrays and slices:
a := [...]float64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} // Array of type [10]float64
a := []float64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} // Slice of type []float64
Just remove the ... and your code will work
[10]float64
and []float64
are distinct types in Go. Your avg
function expects a slice of type float64
but you are instead passing it an array of type [10]float64
. As others have noted, you can either get rid of the ...
in your declaration of a
or you can pass a[:]
to your avg
function.