這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
Golang中的array
在golang中,array是同一類型的元素的有序排列,長度不能更改,佔用記憶體上的一段連續空間。
1)基礎
首先看看array的聲明:
[plain] view plaincopyprint?
- var justiceArray [3]string
var justiceArray [3]string
以上聲明了justiceArray是為有3個元素的string數組,括弧裡面的數字是必須的,不能省略。
另外說明一下,[3]string與[2]string是兩種不同類型的array。
現在對其賦值:
[plain] view plaincopyprint?
- 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{"Superman", "Batman", "Wonder Woman"}fmt.Printf("The Justice League are: %v\n", justiceArray)輸出:The Justice League are: [Superman Batman Wonder Woman] 如果你只想建立一個填充預設值的數組,可以這樣:
[plain] view plaincopyprint?
- justiceArray = [3]string{}
- fmt.Printf("The Justice League are: %v\n", justiceArray)
- 輸出:
- The Justice League are: [ ]
justiceArray = [3]string{}fmt.Printf("The Justice League are: %v\n", justiceArray)輸出:The Justice League are: [ ] 當前數組擁有3個空的字串。
另外你可以用一種省略形式:
[plain] view plaincopyprint?
- justiceArray = [...]string{"Superman", "Batman", "Wonder Woman"}
- fmt.Printf("The Justice League are: %v\n", justiceArray)
- 輸出:
- The Justice League are: [Superman Batman Wonder Woman]
justiceArray = [...]string{"Superman", "Batman", "Wonder Woman"}fmt.Printf("The Justice League are: %v\n", justiceArray)輸出:The Justice League are: [Superman Batman Wonder Woman] 用...代替數字,當然大括弧裡的元素需要跟你聲明的數組長度一致。
目的相同,下面這種聲明賦值就更簡潔了:
[plain] view plaincopyprint?
- avengersArray := [...]string{"Captain America", "Hulk"}
- fmt.Printf("The Avengers are: %v\n", avengersArray)
- 輸出:
- The Avengers are: [Captain America Hulk]
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類型的變數賦值時,是複製整個數組,參照下面這個例子:
[plain] view plaincopyprint?
- 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]
newAvengers := avengersArraynewAvengers[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時,是複製了整個數組,而不是單純的指向。