Go Maps

Go Maps #

Maps in Go store data in key:value pairs. Each element in a map has a key and a value. Maps are unordered, changeable, and do not allow duplicate keys. The length of a map can be obtained using the len() function. By default, an uninitialized map is nil.


Create Maps #

Using var and := #

var a = map[string]string{"brand": "Ford", "model": "Mustang", "year": "1964"}
b := map[string]int{"Oslo": 1, "Bergen": 2, "Trondheim": 3, "Stavanger": 4}

fmt.Printf("a\t%v\n", a)
fmt.Printf("b\t%v\n", b)

Result:

a   map[brand:Ford model:Mustang year:1964]
b   map[Bergen:2 Oslo:1 Stavanger:4 Trondheim:3]

Tip: The order of map elements in the output may differ from the order in the code.


Using make() #

var a = make(map[string]string)
a["brand"] = "Ford"
a["model"] = "Mustang"
a["year"] = "1964"

b := make(map[string]int)
b["Oslo"] = 1
b["Bergen"] = 2
b["Trondheim"] = 3
b["Stavanger"] = 4

fmt.Printf("a\t%v\n", a)
fmt.Printf("b\t%v\n", b)

Result:

a   map[brand:Ford model:Mustang year:1964]
b   map[Bergen:2 Oslo:1 Stavanger:4 Trondheim:3]

Empty Maps #

var a = make(map[string]string)
var b map[string]string

fmt.Println(a == nil) // false
fmt.Println(b == nil) // true

Tip: Always use make() to create an empty map for writing.


Access, Update, Add, and Delete Map Elements #

a := make(map[string]string)
a["brand"] = "Ford"
a["model"] = "Mustang"
a["year"] = "1964"

// Access
fmt.Println(a["brand"]) // Ford

// Update
a["year"] = "1970"

// Add
a["color"] = "red"

// Delete
delete(a, "year")

fmt.Println(a)

Result:

Ford
map[brand:Ford model:Mustang year:1964]
map[brand:Ford color:red model:Mustang year:1970]
map[brand:Ford color:red model:Mustang]

Check for Specific Elements #

a := map[string]string{"brand": "Ford", "model": "Mustang", "year": "1964", "day": ""}

val, ok := a["brand"]
val2, ok2 := a["color"]
_, ok3 := a["model"]

fmt.Println(val, ok)  // Ford true
fmt.Println(val2, ok2) //  false
fmt.Println(ok3)       // true

Tip: The ok variable tells if the key exists in the map.


Maps Are References #

a := map[string]string{"brand": "Ford", "model": "Mustang", "year": "1964"}
b := a

b["year"] = "1970"

fmt.Println(a)
fmt.Println(b)

Result:

map[brand:Ford model:Mustang year:1970]
map[brand:Ford model:Mustang year:1970]

Tip: Changing one map affects other maps that reference the same underlying data.


Iterate Over Maps #

a := map[string]int{"one": 1, "two": 2, "three": 3, "four": 4}

for k, v := range a {
    fmt.Printf("%v : %v, ", k, v)
}

Result (unordered):

two : 2, three : 3, four : 4, one : 1,

Iterate in a Specific Order #

a := map[string]int{"one": 1, "two": 2, "three": 3, "four": 4}
order := []string{"one", "two", "three", "four"}

for _, key := range order {
    fmt.Printf("%v : %v, ", key, a[key])
}

Result:

one : 1, two : 2, three : 3, four : 4,

Tip: Maps are unordered. Use a separate slice to iterate in a specific order.