在错误中使用切片和数组

时间:2017-06-14 19:37:12

标签: arrays go

我正在学习go并且我习惯使用Java所以我遇到了错误,而不是在我看来似乎没有问题。这是我的代码:

WatchEvent

基本上我正在尝试编写一个接受两个数组并将它们反转并交换的方法。

例如:

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}

我得到的错误是这样的:

  

src \ main \ goProject.go:35:不能先使用[type [5] int)作为类型[] int   作为回报论点

     

src \ main \ goProject.go:35:不能使用second(type [5] int)作为类型   [] int in return argument

它说:不能在我的print语句中的变量上使用f(type [5] int)作为类型[] int。

之前我遇到过问题并将tempArrays交换为切片,但我不明白为什么会出现此错误。

旁注:我尝试将参数数组长度替换为......但没有运气:

arr1 = {8,7,6}

arr2 = {3,2,1}

这就产生了与之前相同的错误:

func reverseReverse(first [...]int, second [...]int) ([]int, []int){

所以我的问题是:为什么我会收到此错误?如果需要的话,这是我已经对任何问题发表评论以获取更多信息的所有代码。

下面:

在我将临时数组更改为切片之前,我有这个:

f (type [5]int) as type [...]int

我仍然得到与前面所述相同的错误,但新错误是:

src \ main \ goProject.go:15:非常数数组绑定len(第一个)

src \ main \ goProject.go:16:非常数数组绑定len(第二个)

我理解它应该是常量,但是为什么使用len()不能使它保持不变?

1 个答案:

答案 0 :(得分:2)

几个问题:

  • 您必须先创建一个长度为5的切片,然后才能访问其中的元素。如果你只是做var tempArr1 [] int
  • ,你会感到恐慌
  • 您可以使用切片而不是数组,并且返回类型将与[] int
  • 匹配

你会在这里找到你的解决方案:
https://play.golang.org/p/5E2hL0796o

编辑:允许您将数据类型保存为数组,只需更改要匹配的返回类型即可。您的函数签名应如下所示:

func reverseReverse(first [5]int, second [5]int) ([5]int, [5]int)

GoPlay:
https://play.golang.org/p/_eV3Q0kspQ

要回答你的问题,你不能让函数接受任意大小的数组。你必须指定长度。 Go for [] int和[5] int。

存在根本区别
相关问题