Maps:
Maps
suggest changeMap is an unordered collection of key-value pairs.
Zero value of a map is nil.
Other languages call it a dictionary (C#, Python) or a hash table (C++).
Iteration over a map has a random order. Many languages are different in that respect.
Basics of maps:
m := make(map[string]int)
// set the value
m["three"] = 3
m["four"] = 4
// get the value and see if the value exists
key := "four"
if value, ok := m[key]; ok {
fmt.Printf("Key '%s' exists and maps to %d\n", key, value)
} else {
fmt.Printf("Key '%s' doesn't exists\n", key)
}
key = "five"
if value, ok := m[key]; ok {
fmt.Printf("Key '%s' exists and maps to %d\n", key, value)
} else {
fmt.Printf("Key '%s' doesn't exists\n", key)
}
// if value doesn't exist, the result of lookup is zero value. In this case zero value of int is 0
fmt.Printf("\nValue for non-existing key: %d\n\n", m["not-exists"])
// iterating over keys and values
fmt.Printf("All keys and their values:\n")
for key, value := range m {
fmt.Printf("%s => %d\n", key, value)
}
fmt.Printf("\nBefore deletion: len(m)=%d\n", len(m))
delete(m, "four")
fmt.Printf("After deletion : len(m)=%d\n", len(m))
Key 'four' exists and maps to 4
Key 'five' doesn't exists
Value for non-existing key: 0
All keys and their values:
three => 3
four => 4
Before deletion: len(m)=2
After deletion : len(m)=1
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents
4
Strings
5
Pointers
6
Arrays
7
Slices
8
Maps
9
Structs
10
Interfaces
15
Functions
16
Methods
18
Defer
20
Concurrency
22
Mutex
23
Packages
27
Logging
30
JSON
31
XML
32
CSV
33
YAML
34
SQL
35
HTTP Client
36
HTTP Server
38
Reflection
39
Context
40
Package fmt
41
OS Signals
42
Testing
49
gob
50
Plugin
53
Console I/O
54
Cryptography
59
Contributors