Sobes.tech
Senior

Where will the array and map be located — on the heap or on the stack?

sobes.tech AI

Answer from AI

In Go, arrays are usually allocated on the stack if their size is known at compile time and they are not too large. This is because arrays are fixed-size values. However, if an array is passed as a pointer or used in a structure allocated on the heap, then the array will also be on the heap.

A map in Go is a reference type, internally implemented through a pointer to a data structure on the heap. Therefore, a map is always allocated on the heap, even if the map variable is declared locally.

Example:

func example() {
    var arr [10]int       // array on the stack
    m := make(map[int]int) // map on the heap
    _ = arr
    _ = m
}