Declaration

The KeyType is a comparable type, and ValueType cab be any type.

map[KeyType]ValueType

Comparable type

These are boolean, numeric, string, pointer, channel, and interface types, and structs or arrays that contain only those types. slices, maps, and functions are not comparable.

ch1 := make(chan int)
channelMap := make(map[chan int]string)
channelMap[ch1] = "Channel 1"
var i1 interface{} = 42
var i2 interface{} = "hello"
var i3 interface{} = 42

interfaceMap := make(map[interface{}]string)

interfaceMap[i1] = "Number"
interfaceMap[i2] = "String"

fmt.Println(interfaceMap[i1])  // Number
fmt.Println(interfaceMap[i2])  // String
fmt.Println(interfaceMap[i3])  // Number (i1 and i3 are considered equal)
type Person struct {
    Name string
    Age  int
}
m := make(map[Person]string)
m[Person{Name: "Bob", Age: 25}] = "Designer"

// PersonWithSlice is not a comparable struct
// type PersonWithSlice struct {
//     Name  string
//     Hobbies []string  // Slices are not comparable
// }
m := make(map[[2]int]string)
m[[2]int{1, 2}] = "Point A"

// Slice element type is not comparable
// arr := [2][]int{[]int{1}, []int{2}}

Reference type

Like slices, maps hold references to an underlying data structure, a variable doesn’t point to an initialised map is nil. A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic.

var m map[string]int // nil

If you pass a map to a function that changes the contents of the map, the changes will be visible in the caller.

func modifyMap(m map[string]int) {
    m["key"] = 100
}
m := map[string]int{"key": 1}
modifyMap(m)
fmt.Println(m) // map[key:100]

Built-in functions

The make function allocates a map value that points to it.

m = make(map[string]int)

The len function returns on the number of items in a map.

len(m)

The delete function removes an entry from the map.