dictionarygo

What data structure do Go maps use internally?


I'm interested in the following:


Solution

  • The answer by @ANisus holds true for versions of Go before 1.24. For anyone seeking this information after Feburary 2025 when Go 1.24 was released, the internal map representation now uses an implementation of the swiss map as defined here: https://abseil.io/blog/20180927-swisstables

    As for the structure of the map itself, it is as follows:

    type SwissMapType struct {
        Type
        Key   *Type
        Elem  *Type
        Group *Type // internal type representing a slot group
        // function for hashing keys (ptr to key, seed) -> hash
        Hasher    func(unsafe.Pointer, uintptr) uintptr
        GroupSize uintptr // == Group.Size_
        SlotSize  uintptr // size of key/elem slot
        ElemOff   uintptr // offset of elem in key/elem slot
        Flags     uint32
    }
    

    and the rest of the code can be found here: https://go.dev/src/internal/abi/map_swiss.go

    Regarding hashing and collision management, the new swiss map uses an open-addressed hashtable and it grows incrementally to avoid longer delays when the tables have to grow. A detailed explanation can be found on the Go blog: https://go.dev/blog/swisstable