Maps explained: create, add, get, delete

yourbasic.org/golang

Go maps are implemented by hash tables and have efficient add, get and delete operations.

Create a new map

var m map[string]int                // nil map of string-int pairs

m1 := make(map[string]float64)      // Empty map of string-float64 pairs
m2 := make(map[string]float64, 100) // Preallocate room for 100 entries

m3 := map[string]float64{           // Map literal
    "e":  2.71828,
    "pi": 3.1416,
}
fmt.Println(len(m3))                // Size of map: 2
Warning: If you try to add an element to an uninitialized map you get the mysterious run-time error Assignment to entry in nil map.

Add, update, get and delete keys/values

m := make(map[string]float64)

m["pi"] = 3.14             // Add a new key-value pair
m["pi"] = 3.1416           // Update value
fmt.Println(m)             // Print map: "map[pi:3.1416]"

v := m["pi"]               // Get value: v == 3.1416
v = m["pie"]               // Not found: v == 0 (zero value)

_, found := m["pi"]        // found == true
_, found = m["pie"]        // found == false

if x, found := m["pi"]; found {
    fmt.Println(x)
}                           // Prints "3.1416"

delete(m, "pi")             // Delete a key-value pair
fmt.Println(m)              // Print map: "map[]"

For-each range loop

m := map[string]float64{
    "pi": 3.1416,
    "e":  2.71828,
}
fmt.Println(m) // "map[e:2.71828 pi:3.1416]"

for key, value := range m { // Order not specified 
    fmt.Println(key, value)
}

Starting with Go 1.12, the fmt package prints maps in key-sorted order to ease testing.

Performance and implementation

Go step by step

Core Go concepts: interfaces, structs, slices, maps, for loops, switch statements, packages.

Share this page: