Golang Basics - Maps

Maps are an essential programming tool used to store a collection of key-value pairs. Go has maps natively implemented in the map structure.

// A map takes two types: the type of key and type of value
// Here we initialize a map with a string key type and an int value type
var mileage map[string]int

// Maps can be initialized with their key value pairs:
mileage = map[string]int{
        "BMW": 5,
        "Ford": 4,
}

// Elements can be accessed by specifying the keys
fmt.Println(mileage["Ford"])
// 4

// Keys can be added to existing maps, and existing values can be modified
mileage["Toyota"] = 7
mileage["Ford"] = 6

// A key-value pair can be deleted using the inbuilt `delete` function
delete(mileage, "BMW")

The keys in maps can be of any type except for slices, functions, and maps. Values can be of any type:

type Vehicle struct{
        Model string
        Wheels int
}

car := Vehicle{
        Model: "Toyota",
        Wheels: 4,
}

bike := Vehicle{
        Model: "Ducati",
        Wheels: 2,
}

// We can now delcare a map of a vehicle to its mileage
mileage := map[Vehicle]int{
        car: 7,
        bike: 12,
}

If we try to get the value of a key that does not exist, we will instead get it's zero value:

fmt.Println(mileage["Lexus"])
// 0

We can also explicitly check if the key exists or not:

lexusMileage, exists := mileage["Lexus"]
// The second return value is a boolean variable which is true if the value exists, and false otherwise

fmt.Println(lexusMileage, exists)
// 0, false

📖 Read next: Arrays and slices


Liked this article? Share it on: