Lesson 6 of 60 · Go
Arrays, Slices, and Maps
Duration: 20 minutes
Arrays, Slices, and Maps
Go has three main collection types: arrays for fixed-size data, slices for flexible sequences, and maps for key-value lookup.
Arrays
Arrays have a fixed length and store values of one type.
var a [3]int
var b = [3]string{"a", "b", "c"}
Slices
Slices are views over arrays with dynamic length and capacity.
s := []int{1, 2, 3}
s = append(s, 4, 5)
sub := s[1:4]
Use len(s) for the number of elements and cap(s) for the current capacity.
Maps
Maps store values by key and are useful for lookup tables.
m := make(map[string]int)
m["alice"] = 42
fmt.Println(m["alice"])
Check whether a key exists using the second boolean result.
if v, ok := m["bob"]; ok {
fmt.Println("found", v)
}