Map
A map is a built-in data structure that is used to store a collection of unordered key-value pairs. The pairs can be of the same type or of mixed types. It is Go’s implementation of a hash table, which allows for efficient access, insertion, and deletion.
Syntax
An empty map can be created using the make()
function and assigning it to a variable.
variable_name := make(map[key_data_type]value_data_type)
An empty map can also be created by assigning the variable to a map literal.
variable_name := map[key_data_type]value_data_type{}
Initializing a Map With Existing Key-Value Pairs
A map literal can also be used when initializing values in the declaration.
map_name := map[key_data_type]value_data_type{
key-1: value-1,
key-2: value-2,
key-N: value-N,
}
Note: All pairs should terminate with a comma, including the final pair, unless the assignment is all made on one line.
Accessing Items
A value in the map can be accessed using its corresponding key value by putting the key in brackets.
map_name[key_value]
The value that results from the code above can also be stored in a variable for later use.
variable_name := map_name[key_value]
If the key does not exist, then the zero value will be returned based on the data type of the values in the map (e.g. int : 0, bool : false).
Adding Items
Add new key-value pairs into the map by setting the new key value to a new value.
map_name[new_key] = [new_value]
Removing Items
Key-value pairs can be removed from a map with the built-in delete()
function.
delete(map_name, existing_key)
Examples
Declaring an Empty Map
The following code demonstrates how to create and print an empty map.
package mainimport "fmt"func main() {// Create a empty map called emptyMapemptyMap := make(map[string]int)// Print mapfmt.Println(emptyMap)}
This will output:
map[]
Declaring a Map with Values
The following code demonstrates how to initialize and print a map with key-value pairs.
package mainimport "fmt"func main() {// Initialize map gradebook with valuesgradebook := map[string]float32{"John": 85.2, "Ana": 95.6}// Print map gradebookfmt.Println(gradebook)}
This will output:
map[John:85.2 Ana:95.6]
Accessing Elements
The following code will print the corresponding value for the key "John"
.
// Print the value with key "John"fmt.Println(gradebook["John"])
This will output:
85.2
Iterating All Key/Value Pairs in a Map
The following code will iterate and print all the key/value pairs of the map.
// Iterate all key/value pairs of the gradebook mapfor key, value := range gradebook {fmt.Printf("(%s, %.1f)\n", key, value)}
This will output:
(John, 85.2)(Ana, 95.6)
Storing a Map Value in a Variable
The following code will access the value in a map corresponding to the key of “Ana”. It will store the result in a variable called anaScore
and print it.
// Store the value that has a key of "Ana" in anaScoreanaScore := gradebook["Ana"]fmt.Println(anaScore)
This will output:
95.6
Accessing a Key That Doesn’t Exist
The following code demonstrates what is returned for a non-existent key. The map maps a string to a float.
// Store the value that has a key of "John" in johnScorejohnScore := gradebook["David"]// Since "David" does not exist in the map, 0 will be printedfmt.Println(johnScore)
This will output:
0
Adding Values
The following code will first print an initialized map. It will then add two more key-value pairs into the map and print the map.
// Print the initialized mapfmt.Println(gradebook)// Add more key-value pairsgradebook["George"] = 76.4gradebook["Emma"] = 90// Print the map againfmt.Println(gradebook)
This will output:
map[Ana:95.6 John:85.2]map[Ana:95.6 Emma:90 George:76.4 John:85.2]
Removing Values
The following code will first print an initialized map. It will then remove a key-value pair and print the map.
// Print the initialized mapfmt.Println(gradebook)// Delete an itemdelete(gradebook, "John")// Print the map againfmt.Println(gradebook)
This will output:
map[Ana:95.6 Emma:90 George:76.4 John:85.2]map[Ana:95.6 Emma:90 George:76.4]
Codebyte Example
The following code will summarize all the initializations and operations for a map in Go that has been shown in this document.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Go on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Go
Learn how to use Go (Golang), an open-source programming language supported by Google!Beginner Friendly6 hours