Go Collections
Arrays
An array has a fixed number of elements determined at compile time. Declare one by writing [count] before its type. Array indexes start at 0. Arrays cannot change size, but they are memory-efficient and fast.
package main
import "fmt"
func main() {
a1 := [3]string{}
a1[0] = "Red"
a1[1] = "Green"
a1[2] = "Blue"
fmt.Println(a1[0], a1[1], a1[2])
}
Output:
Red Green Blue
You can initialize values when creating an array.
a1 := [3]string{"Red", "Green", "Blue"}
When the initializer determines the array length, write ... instead of a number.
a1 := [...]string{"Red", "Green", "Blue"}
Slices
A slice can change its number of elements. It has slightly more overhead than an array, but it is flexible.
Unlike an array, a value initialized without an element count is a slice.
a1 := []string{"Red", "Green", "Blue"}
Declare a slice by writing [] before its type. Use append() to add elements.
package main
import "fmt"
func main() {
a1 := []string{} // slice with no initial elements
a1 = append(a1, "Red")
a1 = append(a1, "Green")
a1 = append(a1, "Blue")
fmt.Println(a1[0], a1[1], a1[2])
}
Output:
Red Green Blue
len() returns the length of an array or slice, and cap() returns its capacity. Length is the number of elements in use. Capacity is the number of elements reserved in memory. When a slice exceeds its capacity, Go allocates more memory and copies the existing data.
package main
import "fmt"
func main() {
a := []int{}
for i := 0; i < 10; i++ {
a = append(a, i)
fmt.Println(len(a), cap(a))
}
}
Output:
1 1
2 2
3 4
4 4
5 8
6 8
7 8
8 8
9 16
10 16
Use make(sliceType, initialLength, initialCapacity) to allocate storage for a slice. If the capacity is omitted, it is the same as the initial length. Reserving capacity in advance can reduce reallocations.
bufa := make([]byte, 0, 1024)
Maps
Use map[keyType]valueType to create a map, which stores values by key.
package main
import "fmt"
func main() {
a1 := map[string]int{
"x": 100,
"y": 200,
}
fmt.Println(a1["x"])
a1["z"] = 300
delete(a1, "z")
fmt.Println(len(a1))
_, ok := a1["z"]
if ok {
fmt.Println("Exist")
} else {
fmt.Println("Not exist")
}
for key, value := range a1 {
fmt.Printf("%s=%d\n", key, value)
}
}
Output:
100
2
Not exist
x=100
y=200