关于第一、二部分,这里有一篇文章比我叙述得更好(自备爬梯):http://blog.golang.org/go-slices-usage-and-internals
看过这文章的朋友可以直接忽略此文一二部分。
该篇是第一部分,另外两篇的链接:
Golang中的array与slice(2)
Golang中的array与slice(3)
-------
Golang中的array
1)基础
var justiceArray [3]string
以上声明了justiceArray是为有3个元素的string数组,括号里面的数字是必须的,不能省略。另外说明一下,[3]string与[2]string是两种不同类型的array。
现在对其赋值:
justiceArray = [3]string{"Superman", "Batman", "Wonder Woman"}
fmt.Printf("The Justice League are: %v\n", justiceArray)
输出:
The Justice League are: [Superman Batman Wonder Woman]
如果你只想创建一个填充默认值的数组,可以这样:justiceArray = [3]string{}
fmt.Printf("The Justice League are: %v\n", justiceArray)
输出:
The Justice League are: [ ]
当前数组拥有3个空的字符串。另外你可以用一种省略形式:
justiceArray = [...]string{"Superman", "Batman", "Wonder Woman"}
fmt.Printf("The Justice League are: %v\n", justiceArray)
输出:
The Justice League are: [Superman Batman Wonder Woman]
用...代替数字,当然大括号里的元素需要跟你声明的数组长度一致。目的相同,下面这种声明赋值就更简洁了:
avengersArray := [...]string{"Captain America", "Hulk"}
fmt.Printf("The Avengers are: %v\n", avengersArray)
输出:
The Avengers are: [Captain America Hulk]
等号右边的返回类型是[2]string。2)数组的复制
需要强调一点的是,array类型的变量指代整个数组变量(不同于c中的array,后者是一个指针,指向数组的第一元素);类似与int这些基本类型,当将array类型的变量赋值时,是复制整个数组,参照下面这个例子:
newAvengers := avengersArray
newAvengers[0] = "Spider-Man"
fmt.Printf("The old avengers: %v\n", avengersArray)
fmt.Printf("The new avengers: %v\n", newAvengers)
输出:
The old avengers: [Captain America Hulk]
The new avengers: [Spider-Man Hulk]
上面将avengersArray赋值给newAvengers时,是复制了整个数组,而不是单纯的指向。