Go Maps: Difference between revisions
Jump to navigation
Jump to search
Line 45: | Line 45: | ||
==Indexing Operator== | ==Indexing Operator== | ||
Indexing operator <tt>[[Go Concepts - Operators#.5B.5D|[]]]</tt> returns the value corresponding to the specified key. If the key does not exist, the [[Go Concepts - The Type System#Zero_Value|zero value]] for the value type is returned. | Indexing operator <tt>[[Go Concepts - Operators#.5B.5D|[]]]</tt> 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 [[Go Concepts - The Type System#Zero_Value|zero value]] for the value type is returned. | ||
<pre> | |||
value := m["key"] | |||
value, exists := m["key"] | |||
</pre> | |||
===Assigning a Value to an Uninitialized Map=== | ===Assigning a Value to an Uninitialized Map=== |
Revision as of 02:52, 28 March 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.
Declaration
Long Declaration
var map_identifier map[key_type]value_type
Example of a map of string to ints:
var m map[string]int
Note that maps must be initialized before attempting to write into them, see Assinging a Value to an Unitialized Map.
Declaration and initialization:
var m map[string]string = make(map[string]string)
Short Declaration
m := make(map[string]string)
Short Declaration
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"] value, exists := m["key"]
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.