【发布时间】:2017-06-14 19:37:11
【问题描述】:
我正在学习 go 并且我习惯于使用 Java,所以我遇到了一些错误,但我认为这似乎不是问题。这是我的代码:
package main
import(
"fmt"
)
func main(){
f:= [5]int{1,2,3,4,5}
h:= [5]int{6,7,8,9,10}
fmt.Println(reverseReverse(f,h))
}
func reverseReverse(first []int, second []int) ([]int, []int){
//creating temp arrays to hold the traversed arrays before swapping.
var tempArr1 []int
var tempArr2 []int
//count is used for counting up the tempArrays in the correct order in the For loops
var count = 0
//goes through the first array and sets the values starting from the end equal to the temp array
//which increases normally from left to right.
for i :=len(first)-1; i>=0;i--{
tempArr1[count] = first[i]
count++
}
count =0
//same as first for loop just on the second array
for i :=len(second)-1; i>=0;i--{
tempArr2[count] = second[i]
count++
}
//trying to replace the values of the param arrays to be equal to the temp arrays
first=tempArr2
second = tempArr1
//returning the arrays
return first,second
}
基本上,我正在尝试编写一个方法,该方法采用两个数组并将它们颠倒和交换返回。
例如:
arr1 = {1,2,3}
arr2 = {6,7,8}
应该返回:
arr1 = {8,7,6}
arr2 = {3,2,1}
我得到的错误是这样的:
src\main\goProject.go:35: 不能使用 first (type [5]int) 作为 type []int 作为回报参数
src\main\goProject.go:35: 不能使用第二个(类型 [5]int)作为类型 []返回参数中的int
它说:不能在我的打印语句中的变量上使用 f (type [5]int) 作为 type []int。
我之前遇到问题并将我的 tempArrays 交换为切片,但我不明白为什么会出现此错误。
旁注:我尝试将参数数组长度替换为 ... 也没有运气:
func reverseReverse(first [...]int, second [...]int) ([]int, []int){
这产生了和之前一样的错误,只是说:
f (type [5]int) as type [...]int
所以我的问题是:为什么会出现这个错误?如果需要,这是我评论任何问题以获取更多信息的所有代码。
这里:
在我将临时数组更改为切片之前,我有这个:
var tempArr1 [len(first)]int
var tempArr2 [len(second)]int
我仍然收到与之前所述相同的错误,但新的错误是:
src\main\goProject.go:15: 非常量数组绑定 len(first)
src\main\goProject.go:16: 非常量数组绑定 len(second)
而且我知道它应该是恒定的,但为什么使用 len() 不能使其恒定?
【问题讨论】:
-
[]int和[5]int是不同的类型。只需使用切片。您的错误与您发布的来源不对应,但摆脱数组无论如何都会修复它们。 -
@JimB 我希望它使用数组,但是当我使用所有数组时我也遇到了错误,有没有办法可以使用所有数组?我将对其进行编辑以显示没有接头的情况以及我遇到的错误。
-
我对其进行了编辑以显示拼接之前的内容。如果可能的话,我想使用数组我相信拼接也可以,但我想用数组来做概念证明。
-
(first [...]int, second [...]int)不是有效的语法,编译器会告诉你。您的参数是切片,因此要么将它们设为数组,要么在整个过程中使用切片。 -
根据定义,常量在编译时是已知的。
len()在运行时计算,因此不能是常量。