Using maps
May 12, 2023
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
:
x := make(map[string]string) // x is an empty map of string to string
Not mentioned in this section, you can also create a map with a composite literal expression:
x := map[string]string{} // x is an empty map of string to string
y := map[string]string{ // y is a map of string to string with two key/value pairs
"cow": "moo",
"pig": "oink",
}
To read a map value, you use an index expression:
sound := y["cow"] // sound equals "moo"
To assign a value (or re-assign, if the key already exists), you use an assignment statement:
y["duck"] = "quack" // y now contains three key/value pairs
And to delete a value, you use the built-in delete
function:
delete(y, "pig") // y now contains two key/value pairs
And finally one last usability note:
… A
nil
map is equivalent to an empty map except that no elements may be added.
A nil
map can be created by declaring a variable without an assignment:
var z map[string]string // z is a nil map of string to string
z["foo"] = "bar" // Runtime panic: assignment to entry in nil map
Quotes from The Go Programming Language Specification Version of December 15, 2022