Declare and initialize a map

suggest change

You define a map using the keyword map, followed by the types of its keys and its values:

// Keys are ints, values are ints.
var m1 map[int]int // initialized to nil

// Keys are strings, values are ints.
var m2 map[string]int // initialized to nil

A map variable's zero value is nil. The map header points at shared buckets, so copying the variable does not copy the entries. Writes to a nil map panic. Reads from a nil map return the zero value.

To initialize a map, use the make function:

m := make(map[string]int)

With the two-parameter form of make, it’s possible to specify an initial entry capacity for the map, overriding the default capacity:

m := make(map[string]int, 30)

make with a size hint of 0 still returns a non-nil empty map. That matters for JSON: a nil map encodes as null, while an empty non-nil map encodes as {}.

m := make(map[string]int, 0)

You can also make a map and set its initial value with curly brackets ({}).

var m map[string]int = map[string]int{"Foo": 20, "Bar": 30}

fmt.Println(m["Foo"]) // outputs 20

All the following statements result in the variable being bound to the same value.

// Declare, initializing to zero value, then assign a literal value.
var m map[string]int
m = map[string]int{}

// Declare and initialize via literal value.
var m = map[string]int{}

// Declare via short variable declaration and initialize with a literal value.
m := map[string]int{}

We can also use a map literal to create a new map with some initial key/value pairs.

The key type can be any comparable type; notably, this excludes functions, maps, and slices. The value type can be any type, including custom types or interface{}.

type Person struct {
    FirstName string
    LastName  string
}

// Declare via short variable declaration and initialize with make.
m := make(map[string]Person)

// Declare, initializing to zero value, then assign a literal value.
var m map[string]Person
m = map[string]Person{}

// Declare and initialize via literal value.
var m = map[string]Person{}

// Declare via short variable declaration and initialize with a literal value.
m := map[string]Person{}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents