[Golang]也许有你不知道的,Array和Slice(1)
Golang中的array
1)基础
- var 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: [ ]
另外你可以用一种省略形式:
- 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)数组的复制
需要强调一点的是,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]
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。