Go Maps: Difference between revisions
Line 39: | Line 39: | ||
</pre> | </pre> | ||
A map declaration and initialization with a map literal: | |||
<pre> | <pre> |
Revision as of 17:42, 12 April 2016
External
- Go Specification - Deletion of Map elements https://golang.org/ref/spec#Deletion_of_map_elements
Internal
Overview
A map is an unordered collection of key-value pairs. The map implementation uses the key as an index, quickly retrieving the associated value.
Lexically, a map type is a reference type. The map instances must be initialized before attempting to use into them, either by using the make() function or a map literal, otherwise you will get a runtime error, because a zero value for a map is nil:
panic: assignment to entry in nil map
Implementation Details
In order to store a key/value pair in the map, the map hash function is applied to the key, which produces the index of a bucket. The purpose of the hash function is to generate the index that is evenly distributed across the bucket population. Once a bucket is selected, the map stores the key/value pair in the bucket.
In order to retrieve the value corresponding to a key, the same hash function is applied to select the bucket, and then the map iterates over the keys stored in that bucket.
Declaration
Long Declaration
var map_identifier map[key_type]value_type
Example of a map of string to ints:
var m map[string]int
A map declaration and initialization with a map literal:
var m map[string]string = make(map[string]string)
Short Declaration
m := make(map[string]string)
m := map[string]string { "A": "B", "C": "D", }
Map Operators and Functions
Indexing Operator
Indexing operator [] returns the copy of the value corresponding to the specified key and a boolean value that says whether the key exists or not. If the key does not exist, the zero value for the value type is returned.
value := m["key"] // only the first return value can be used, as long as we are prepared to deal with the zero value value, exists := m["key"]
Idiom:
if value, exists := m["key"]; exists { // it exists ... }
Map Length
len() returns the number of keys.
delete()
Removes the element corresponding to the given key from the map:
delete(m, "something")
It is a no-op if the key does not exist.
make()
The make() function creates the map:
m := make(map[key_type]value_type)
Note that make() returns the map instance, not a pointer.