Go map
Brief introduction to maps
A map is a collection of key-value pairs where each key is unique. It can represent a large number of real-world objects, such as:
- a phone book (where the keys are names and the values are phone numbers),
- a dictionary (where the keys are words and the values are definitions),
- a list of students (where the keys are student IDs and the values are student names),
- etc.
In Go, the type of a map is map[keyType]valueType
(e.g. map[string]int
).
Creating a map (with and without make)
There are two ways to create a map:
- Using the
make
function
m := make(map[string]int)
- Using a map literal
m := map[string]int{
"foo": 1,
"bar": 2,
}
In the first case, m
will be empty, whereas in the second case, m
will contain two key-value pairs.
Retrieving values from a map
In order to retrieve a value from a map, we can use the following syntax:
v, ok := m[key]
v
will be the value associated with key
, and ok
will be a boolean value that indicates whether the key was found in the map.
Let's see an example:
package main
import "fmt"
func main() {
m := map[string]int{
"foo": 1,
"bar": 2,
}
v, ok := m["foo"]
fmt.Println(v, ok) // 1 true
v, ok = m["baz"]
fmt.Println(v, ok) // 0 false
}
Note: In case ok
is false
, v
will be the zero value of the map's value type (e.g. 0
for int
).
Updating values in a map in Go
The syntax for updating a value in a map is the same as for adding a new key-value pair:
m[key] = value
For Example:
package main
import "fmt"
func main() {
// create a map
books := map[string]string{"Go": "In Stock", "Python": "Sold Out"}
fmt.Println("Before Update: ", books)
// changing the value of Go
books["Go"] = "Sold Out"
fmt.Println("After update: ", books)
}
Output
Before Update: map[Go:In Stock Python:Sold Out]
After update: map[Go:Sold Out Python:Sold Out]
That's all there is to it!
Adding an Element to the map in Go
So far, we have created predefined elements in the map. Let us look at how to add new elements to the map.
To add an element to the map, create a new key and assign a value to it using the assignment operator =
package main
import "fmt"
func main() {
// create a map
books := map[string]string{"Go": "In Stock", "Python": "Sold Out"}
fmt.Println("Before Addition: ", books)
// Add new key/value to books
books["Java"] = "In Stock"
fmt.Println("After Addition: ", books)
}
Output
Before Addition: map[Go:In Stock Python:Sold Out]
After Addition: map[Go:In Stock Java:In Stock Python:Sold Out]
Deleting Element from the map in Go
We can delete an element in the map using the delete()
function.
The delete()
method takes two arguments
- name: name of the map
- key: the key of an element that you need to delete from the map
For Example:
package main
import "fmt"
func main() {
// create a map
books := map[string]string{"Go": "In Stock", "Python": "Sold Out"}
fmt.Println("Before Deletion: ", books)
// delete Python element
delete(books, "Python")
fmt.Println("After Deletion: ", books)
}
Output
Before Deletion: map[Go:In Stock Python:Sold Out]
After Deletion: map[Go:In Stock]
Iterating over a map in Go
In order to iterate over a map, we can use a for
loop:
for key, value := range m {
// do something with key and value
}
The only difference with the for
loop for arrays and slices is that the first value returned by the range
expression is the key not the index.
Example
To see maps in action, let's build a simple program that counts the number of occurrences of each word in a string:
package main
import "fmt"
func main() {
s := "to be or not to be that is the question"
words := strings.Split(s, " ")
counts := make(map[string]int)
for _, word := range words {
counts[word]++
}
fmt.Println(counts)
}
"to" and "be" are the most common words in the string s
and they both appear twice.
With this kind of program and (way) larger strings, we could find the most common words in the English language.