GoGo · Lesson 5 of 8

Slices & Maps

Go's two primary collection types. Slices are dynamic arrays. Maps are hash tables. Together they cover nearly everything.

Go
package main

import (
    "fmt"
    "sort"
)

func main() {
    // Slices (dynamic arrays)
    nums := []int{1, 2, 3, 4, 5}
    fmt.Println(nums[0])          // 1
    fmt.Println(nums[1:3])        // [2 3]
    fmt.Println(len(nums))        // 5
    fmt.Println(cap(nums))        // capacity (may be > len)

    // append — may reallocate
    nums = append(nums, 6, 7, 8)
    fmt.Println(nums)   // [1 2 3 4 5 6 7 8]

    // Spread operator for appending a slice
    more := []int{9, 10}
    nums = append(nums, more...)

    // make — allocate with size and capacity
    s := make([]int, 5)      // len=5, all zeros
    s2 := make([]int, 0, 10) // len=0, cap=10

    // copy
    src := []int{1, 2, 3}
    dst := make([]int, len(src))
    copy(dst, src)

    // 2D slice
    matrix := [][]int{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
    }
    fmt.Println(matrix[1][2])   // 6

    // Sorting
    data := []int{5, 2, 8, 1, 9, 3}
    sort.Ints(data)
    fmt.Println(data)   // [1 2 3 5 8 9]

    words := []string{"banana", "apple", "cherry"}
    sort.Strings(words)
    fmt.Println(words)  // [apple banana cherry]

    _ = s; _ = s2
}
Go
package main

import "fmt"

func main() {
    // Maps (hash tables)
    ages := map[string]int{
        "Alice": 30,
        "Bob":   25,
        "Carol": 35,
    }

    fmt.Println(ages["Alice"])   // 30

    // Check if key exists
    age, ok := ages["Dave"]
    if !ok {
        fmt.Println("Dave not found")
    }
    _ = age

    // Add and update
    ages["Dave"] = 28
    ages["Alice"] = 31  // update

    // Delete
    delete(ages, "Bob")

    // Iterate (order is random)
    for name, age := range ages {
        fmt.Printf("%s: %d\n", name, age)
    }

    // Map of slices
    groups := map[string][]string{
        "fruits":     {"apple", "banana", "cherry"},
        "vegetables": {"carrot", "broccoli"},
    }
    groups["fruits"] = append(groups["fruits"], "date")
    fmt.Println(groups)

    // make a map
    m := make(map[string]int)
    m["key"] = 42
    fmt.Println(m)
}
⚠ Warning
Slices are reference types — assigning a slice to another variable does not copy the data; both point to the same underlying array. Use copy() or append([]int{}, src...) to make an independent copy.