SyntaxStudy
Sign Up
Go Pointers, Slices, and Maps
Go Beginner 1 min read

Pointers, Slices, and Maps

Go has pointers but no pointer arithmetic, making them safer than C pointers. A pointer holds the memory address of a value. You obtain the address of a variable with the `&` operator and dereference it with `*`. Pointers are commonly used to allow functions to modify their arguments and to avoid copying large data structures. Slices are a flexible, dynamic view over an underlying array. Unlike arrays, slices can grow and shrink using the built-in `append` function. A slice has three components: a pointer to the underlying array, a length, and a capacity. Understanding this structure explains why appending to a slice passed to a function does not affect the caller unless the slice is returned or a pointer to it is used. Maps are Go's built-in hash table type. They are declared with `map[KeyType]ValueType` and initialised with `make` or a map literal. Reading a missing key returns the zero value for the value type; the two-value form `v, ok := m[key]` lets you distinguish between a stored zero and an absent key. Maps are not safe for concurrent use without synchronisation.
Example
package main

import "fmt"

func increment(n *int) {
    *n++
}

func main() {
    // Pointers
    x := 10
    p := &x
    fmt.Println("x =", x, "  *p =", *p)
    increment(&x)
    fmt.Println("after increment, x =", x)

    // Arrays vs slices
    arr := [3]int{1, 2, 3}      // fixed-size array
    sl  := arr[:]                // slice of the array
    sl = append(sl, 4, 5)        // grows beyond original array
    fmt.Println("arr:", arr)     // unchanged
    fmt.Println("sl :", sl)

    // make a slice directly
    nums := make([]int, 0, 5)
    for i := 0; i < 5; i++ {
        nums = append(nums, i*i)
    }
    fmt.Println("squares:", nums)

    // Maps
    scores := map[string]int{
        "Alice": 95,
        "Bob":   87,
    }
    scores["Carol"] = 91

    if v, ok := scores["Dave"]; ok {
        fmt.Println("Dave:", v)
    } else {
        fmt.Println("Dave not found, zero value:", v)
    }

    for name, score := range scores {
        fmt.Printf("%s: %d\n", name, score)
    }
}