Map types

May 10, 2023

Map types

A map is an unordered group of elements of one type, called the element type, indexed by a set of unique keys of another type, called the key type. The value of an uninitialized map is nil.

MapType     = "map" "[" KeyType "]" ElementType .
KeyType     = Type .

Maps should be familiar to just about anyone who’s familiar with programming, by one name or another. “Hashmaps,” “dictionaries,” “associative arrays,” or even simply “objects” in JavaScript or JSON.

In contrast to many dynamic languages, all values in a map must be of the same type in Go. So while the following is valid in JavaScript (or close equivalents in many other languages), the same is not possible in Go:

var obj = {
  "name": "Bob",
  "age": 32
};

You can kind of get around this in Go by using the empty interface (aka any):

var obj = map[string]any{
  "name": "Bob",
  "age":  32,
}

But this makes dereferencing more complicated, because a type assertion becomes necessary to convert the keys to their underlying types. Type assertio we’ll cover in greater detail later.

Quotes from The Go Programming Language Specification Version of December 15, 2022

Share this

Related Content

Type identities of compound types

So we now know that types are either identical or different. let’s look at the details, with examples. Type identity … In detail: Two array types are identical if they have identical element types and the same array length. So given: type ( X = [10]int Y = X Z [10]int ) Types X, Y, and [10]int are identical to each other, but not to [9]int or [10]int32. Type Z is also different from all the others, due to the fact that it is a named type.

Map length and capacity

Maps, like arrays and slices, have length. Map types … The number of map elements is called its length. For a map m, it can be discovered using the built-in function len and may change during execution. … This should be straight forward, but let’s consider a couple examples for good measure: x := map[string]int{"a": 1, "b": 2, "c": 3} fmt.Println(len(x)) // 3 var y map[string]float64 fmt.Println(len(y)) // 0 And somewhat deceptively, their capacity can also be set, or at least hinted at, but not read.

Using maps

Today I’m jumping around a bit, for the sake of coherence. Map types … [Map] elements may be added during execution using assignments and retrieved with index expressions; they may be removed with the delete built-in function. A new, empty map value is made using the built-in function make, … Let’s summarize with examples. We’ll dive into details as the relevant portions of the spec come up. To create a map, you use the built-in function make: