首先看看array的声明:
[plain]
view plain
copy
print
?
- varjusticeArray[3]string
var justiceArray [3]string
以上声明了justiceArray是为有3个元素的string数组,括号里面的数字是必须的,不能省略。
另外说明一下,[3]string与[2]string是两种不同类型的array。
现在对其赋值:
[plain]
view plain
copy
print
?
- justiceArray=[3]string{"Superman","Batman","WonderWoman"}
- fmt.Printf("TheJusticeLeagueare:%vn",justiceArray)
- 输出:
- TheJusticeLeagueare:[SupermanBatmanWonderWoman]
justiceArray = [3]string{"Superman","Wonder Woman"}
fmt.Printf("The Justice League are: %vn",justiceArray)
输出:
The Justice League are: [Superman Batman Wonder Woman]
如果你只想创建一个填充默认值的数组,可以这样:
[plain]
view plain
copy
print
?
- justiceArray=[3]string{}
- fmt.Printf("TheJusticeLeagueare:%vn",justiceArray)
- 输出:
- TheJusticeLeagueare:[]
justiceArray = [3]string{}
fmt.Printf("The Justice League are: %vn",justiceArray)
输出:
The Justice League are: [ ]
当前数组拥有3个空的字符串。
另外你可以用一种省略形式:
[plain]
view plain
copy
print
?
- justiceArray=[...]string{"Superman",justiceArray)
- 输出:
- TheJusticeLeagueare:[SupermanBatmanWonderWoman]
justiceArray = [...]string{"Superman",justiceArray)
输出:
The Justice League are: [Superman Batman Wonder Woman]
用...代替数字,当然大括号里的元素需要跟你声明的数组长度一致。
目的相同,下面这种声明赋值就更简洁了:
[plain]
view plain
copy
print
?
- avengersArray:=[...]string{"CaptainAmerica","Hulk"}
- fmt.Printf("TheAvengersare:%vn",avengersArray)
- 输出:
- TheAvengersare:[CaptainAmericaHulk]
avengersArray := [...]string{"Captain America","Hulk"}
fmt.Printf("The Avengers are: %vn",avengersArray)
输出:
The Avengers are: [Captain America Hulk]
等号右边的返回类型是[2]string。
2)数组的复制
需要强调一点的是,array类型的变量指代整个数组变量(不同于c中的array,后者是一个指针,指向数组的第一元素);
类似与int这些基本类型,当将array类型的变量赋值时,是复制整个数组,参照下面这个例子:
[plain]
view plain
copy
print
?
- newAvengers:=avengersArray
- newAvengers[0]="Spider-Man"
- fmt.Printf("Theoldavengers:%vn",avengersArray)
- fmt.Printf("Thenewavengers:%vn",newAvengers)
- 输出:
- Theoldavengers:[CaptainAmericaHulk]
- Thenewavengers:[Spider-ManHulk]
newAvengers := avengersArray
newAvengers[0] = "Spider-Man"
fmt.Printf("The old avengers: %vn",avengersArray)
fmt.Printf("The new avengers: %vn",newAvengers)
输出:
The old avengers: [Captain America Hulk]
The new avengers: [Spider-Man Hulk]
上面将avengersArray赋值给newAvengers时,是复制了整个数组,而不是单纯的指向。