Go Maps: Difference between revisions
Line 9: | Line 9: | ||
=Overview= | =Overview= | ||
A map is an unordered collection of key-value pairs. | A map is an unordered collection of key-value pairs. | ||
Lexically, a map type is a [[Go_Concepts_-_The_Type_System#Reference_Types|reference type]] and in order to get an instance of it, you need to use the <tt>[[#make.28.29|make()]]</tt> function. Note that maps must be initialized before attempting to write into them, otherwise you will get a runtime error on write. This is because a [[Go_Concepts_-_The_Type_System#Zero_Value|zero value]] for a map is <tt>nil</tt> Also see [[Go Maps#Assigning_a_Value_to_an_Uninitialized_Map|Assinging a Value to an Unitialized Map]]. | |||
=Declaration= | =Declaration= |
Revision as of 19:38, 2 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.
Lexically, a map type is a reference type and in order to get an instance of it, you need to use the make() function. Note that maps must be initialized before attempting to write into them, otherwise you will get a runtime error on write. This is because a zero value for a map is nil Also see Assinging a Value to an Unitialized Map.
Declaration
Long Declaration
var map_identifier map[key_type]value_type
Example of a map of string to ints:
var m map[string]int
Declaration and initialization:
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 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 ... }
Assigning a Value to an Uninitialized Map
If the indexing operator is also used to assign a value to a key for an uninitialized map, we get a runtime error:
panic: assignment to entry in nil map
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.