How Pointers Work with Slices and Maps in Go

Slices and maps in Go are reference types that share underlying data, allowing functions to modify the original values directly without explicit pointers.

In Go, slices and maps are reference types that internally hold a pointer to their underlying data, so passing them to functions allows the function to modify the original data without using explicit pointers. When you pass a slice or map, you are passing a copy of the header (which contains the pointer), but both the caller and callee point to the same underlying array or hash table.

func modifySlice(s []int) {
    s[0] = 99 // Modifies the underlying array shared by caller
}

func modifyMap(m map[string]int) {
    m["key"] = 1 // Modifies the underlying map shared by caller
}

func main() {
    s := []int{1, 2, 3}
    modifySlice(s)
    // s is now [99, 2, 3]

    m := map[string]int{"key": 0}
    modifyMap(m)
    // m is now map[key:1]
}