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