在Go语言里向函数传递数组,到底有几种方式?事实上只有一种,就是传递固定长度的数组。网上有些文章甚至是教程说有两种:“固定长度和非固定长度的数组”,这种说法混淆了数组和切片,这是两种完全不同的类型(切片是一种结构体包括一个指向数组的指针,长度和容量)这一点类似于java里的数组与ArrayList。不仅如此,不同长度的数组也是不同类型的参数。具体验证可以如下示例:
package main
import "fmt"
//以数组为参数
func print1(arr [3]string) {
fmt.Printf("%T\n", arr)
for i := 0; i < len(arr); i++ {
fmt.Printf("%s\n", arr[i])
}
}
//以切片为参数
func print2(sl []string) {
fmt.Printf("%T\n", sl)
for i := 0; i < len(sl); i++ {
fmt.Printf("%s\n", sl[i])
}
}
func main() {
var a [3]string
a[0] = "how"
a[1] = "are"
a[2] = "you"
//正确: 数组传递为数组
print1(a)
b := make([]string, 3)
b[0] = "how"
b[1] = "are"
b[2] = "you"
//正确: 切片传递为切片
print2(b)
//错误:切片不能传递为数组,长度相同也不行
print1(b)
//错误:数组不能传递为切片,长度相同也不行
print2(a)
var c [2]string
c[0] = "how"
c[1] = "are"
//错误:数组长度不同也属于不同的参数类型
print1(c)
}
[root@dev ] go run arrcheck.go
# command-line-arguments
./arrcheck.go:34:11: cannot use b (type []string) as type [3]string in argument to print1
./arrcheck.go:35:11: cannot use a (type [3]string) as type []string in argument to print2
./arrcheck.go:41:8: cannot use c (type [2]string) as type [3]string in argument to print1