Map is an unordered collection of key-value pairs where each key is unique and implements hash-table data structure that offer fast lookups, adds and deletes. They are also called associative arrays or dictionaries.
They are perfert for searching values. If given the key, the associated value can be retrieved very quickly.
Creating map
1 |
var map1 map[keytype]valuetype |
A map can be created by several ways.
Declaring a variable of type map:
1 |
var myMap map[int]string |
Using make
keyword:
1 |
myMap := make(map[string]int) |
The value of an uninitialized map is nil.
The key type can be any type for which the operations == and != are defined, like string, int, and float
Add element to map
1 2 3 4 5 6 7 8 9 10 11 12 |
package main import "fmt" func main() { // create a map countries := map[int]string{1: "USA", 2: "Spain"} fmt.Println("Initial Map: ", students) // add element with key 3 countries[3] = "Italy" // add element with key 5 countries[5] = "Brasil" fmt.Println("Updated Map: ", countries) } |
Output:
1 2 |
Initial Map: map[1:USA 2:Spain] Updated Map: map[1:USA 2:Spain 3:Italy 5:Brasil] |
Iteration over map
1 2 3 4 5 6 |
myMap := make(map[int]string) myMap[1] = "a" myMap[2] = "b" for key, value := range myMap { fmt.Println(key, value) } |
Remember that order of map elements is not specified. It means that result iteration over map is not guranteed to be the same.
Delete an element with a key of map
Deleting an element of the map is done with the delete()
function.
1 2 3 4 5 6 7 8 9 10 |
package main import "fmt" func main() { // create a map fruitsCount := map[string]int{"Apple": 30, "Banana": 15, "Lemon": 20} fmt.Println("Initial Map: ", fruitsCount) // remove element of map with key Banana delete(personAge, "Banana") fmt.Println("Updated Map: ", fruitsCount) } |
Output:
1 2 |
Initial Map: map[Apple:30 Banana:15 Lemon:20] Updated Map: map[Apple:30 Lemon:20] |