英文:
Working with arrays in go, cannot compile code due to mismatched types
问题
所以我正在尝试在Go语言中编译以下代码,我几个小时前才开始学习:
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
}
我收到一个错误,说我不能传递长度为10的数组,因为该函数的定义是[]float64数组。有没有解决这个问题的方法,或者我是否遗漏了一些明显的东西?
英文:
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?
答案1
得分: 5
你将a定义为长度为length的数组,在avg函数中,你期望得到一个float64类型的切片。
如果你不需要固定长度,可以将a定义为切片:
a := []float64{...}
或者你可以将array转换为切片:
sum := avg(a[:])
英文:
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[:])
答案2
得分: 3
你正在混淆数组和切片:
a := [...]float64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} // 类型为 [10]float64 的数组
a := []float64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} // 类型为 []float64 的切片
只需移除 "...",你的代码就可以正常工作了。
英文:
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
答案3
得分: 0
[10]float64 和 []float64 是 Go 语言中不同的类型。你的 avg 函数期望接收一个 float64 类型的切片,但你却传递了一个类型为 [10]float64 的数组。正如其他人指出的,你可以在声明 a 时去掉 ...,或者将 a[:] 传递给你的 avg 函数。
英文:
[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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论