A hash table is an unordered collection of key/value pairs in which all the keys are distinct, and the value associated with a given key can be retrieved, updated, or removed using a constant number of key comparisons on the average, no matter how large the hash table.
A go map is a reference to a hash table and is written map[K]V
where K
and
V
are the types of it's keys and values. K
must be comparable using ==
, so
that the map can test is a given key already exists within. Floating point
numbers are comparable, but it's a bad idea to compare floats for equality,
especially if NaN
is a possible value.
exists?
A map lookup actually returns two values. The first being the actual value held
by that key OR the zero value for that type. The second value returned is a
boolean indicating whether the value was in the map or if a zero value was used.
This was you can differentiate between an existing zero value and a non-existing
entry. It's common practice to name this boolean ok
and check it inline:
if val, ok := dict["foo"]; ok {
//do something here
}
creation
ages := make(map[string]int)
// We can also use a map literal to create a map populated with some initial
// pairs:
ages := map[string]int{
"alice": 31,
"charlie": 34,
}
// This is equivalent
ages := make(map[string]int)
ages["alice"] = 31
ages["charlie"] = 34
deletion
delete(ages, "alice")
Lookup or deletion are safe even if the key does not exist. The zero value for that type will be returned.