Lab 03: Arrays, Slices & Maps

Objective

Master Go's core collection types: arrays (fixed-size), slices (dynamic), and maps (hash tables). Understand how slices share underlying arrays and avoid common pitfalls.

Time

30 minutes

Prerequisites

  • Lab 01–02

Tools

  • Docker image: zchencow/innozverse-go:latest


Lab Instructions

Step 1: Arrays

docker run --rm zchencow/innozverse-go:latest go run - << 'EOF'
package main

import "fmt"

func main() {
    // Arrays are value types — fixed size is part of the type
    var a [5]int
    fmt.Println("Zero array:", a)

    b := [5]int{10, 20, 30, 40, 50}
    c := [...]int{1, 2, 3, 4, 5}   // compiler counts elements

    fmt.Println("b:", b)
    fmt.Println("c:", c)
    fmt.Println("len:", len(b), len(c))

    // 2D array
    grid := [3][3]int{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
    }
    for _, row := range grid {
        fmt.Println(row)
    }

    // Array comparison — arrays are comparable
    x := [3]int{1, 2, 3}
    y := [3]int{1, 2, 3}
    z := [3]int{1, 2, 4}
    fmt.Println("x==y:", x == y)
    fmt.Println("x==z:", x == z)

    // Arrays are COPIED on assignment (unlike slices)
    d := b
    d[0] = 999
    fmt.Println("b[0]:", b[0], "d[0]:", d[0]) // b unchanged
}
EOF

💡 Arrays in Go are value types — assigning an array copies all its elements. [5]int and [6]int are completely different types. In practice, you'll use slices 95% of the time — arrays are mainly used to create slices or when you need a fixed-size, comparable value type.

📸 Verified Output:


Step 2: Slices — The Workhorse

💡 A slice is a 3-field struct: pointer, length, cap. When you do a := s[1:4], both a and s point to the same underlying array. Modifying a[0] modifies s[1]. Use copy() to make truly independent slices. append() returns a new slice — always reassign: s = append(s, val).

📸 Verified Output:


Step 3: Slice Operations

📸 Verified Output:


Step 4: Maps

💡 Always use the two-value form v, ok := m[key] when you need to distinguish "key missing" from "key present with zero value". m["missing"] returns 0/""/false/nil — no error, no panic. Maps are reference types (like slices) — passing a map to a function doesn't copy it.

📸 Verified Output:


Steps 5–8: Set, Frequency Count, Invert Map, Capstone Word Frequency Analyzer

📸 Verified Output:


Summary

Type
Declare
Dynamic
Comparable
Reference?

Array

[N]T

❌ (value)

Slice

[]T

Map

map[K]V

Further Reading

Last updated