英文:
Why is my array declaration not working as expected?
问题
新手学习Go语言。为什么我在这种方式声明数组时会得到一个编译时错误?
func CountPositivesSumNegatives(numbers []int) []int {
// 编译时错误:无法将 result(类型为 [2]int)作为返回参数中的 []int 类型使用
var result [2]int
for _,number := range numbers {
if (number > 0) {
result[0] += 1
} else {
result[1] += number
}
}
return result
}
如果我将代码更改为以下方式,它可以工作,但我不确定为什么?
func CountPositivesSumNegatives(numbers []int) []int {
result := []int{0,0}
for _,number := range numbers {
if (number > 0) {
result[0] += 1
} else {
result[1] += number
}
}
return result
}
英文:
Newbie to Go here. Why am I getting a compile time error when I declare an array this way ?
func CountPositivesSumNegatives(numbers []int) []int {
// Compile Time Error : cannot use result (type [2]int) as type []int in return argument
var result [2]int
for _,number := range numbers {
if (number > 0) {
result[0] += 1
} else {
result[1] += number
}
}
return result
}
If I change the code to be this way, it works , but I am not sure why ?
func CountPositivesSumNegatives(numbers []int) []int {
result := []int{0,0}
for _,number := range numbers {
if (number > 0) {
result[0] += 1
} else {
result[1] += number
}
}
return result
}
答案1
得分: 2
Go编译器在这里告诉你确切的错误:
"编译时错误:无法将结果(类型为[2]int)用作返回参数中的[]int类型" - 声明的返回类型和返回值的类型不匹配。
你的函数CountPositiveSumNegatives()
的返回类型声明为[]int
(整数切片),但你返回的类型是[2]int
(包含2个元素的整数数组)。
要修复你的第一个示例,你需要将返回类型更改为[2]int
:
func CountPositivesSumNegatives(numbers []int) [2]int {
或者,正如你发现的那样,你可以将结果改为整数切片。
要了解有关数组和切片以及它们之间的区别的更多信息,我推荐阅读官方Go博客文章Go Slices: usage and internals。
英文:
Go compiler is telling you the exact error here:
"Compile Time Error : cannot use result (type [2]int) as type []int in return argument" - declared return type and type of returned value do not match.
Your function CountPositiveSumNegatives()
return type is declared as []int
(slice of integers) but type of what you return is [2]int
(2 element integer array).
To fix your first example you need to change return type to [2]int
func CountPositivesSumNegatives(numbers []int) [2]int {
Or as you found out you can make result an integer slice.
To read more about arrays and slices and difference between them I recommend this official Go Blog post called Go Slices: usage and internals
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论