Exploring Maps in Go

Welcoming Maps

Having explored slices and arrays, let's take another step in our Go journey. Imagine you're traveling and need to remember the capitals of various countries. While you could memorize each one individually, wouldn't it be more efficient to have a map that links each country to its capital? In Go, maps allow you to establish such relationships between keys and values, like countries and their capitals.

Here's how we create a map in Go:

// Creating a simple map to hold the country as key and its capital as value
capitalCities := map[string]string{
    "France": "Paris",
    "Japan": "Tokyo",
    "Kenya": "Nairobi",
}

In Go, declaring a map involves specifying the types for both the keys and the values that the map will hold. The map keyword is followed by square brackets containing the key's type, while the value's type follows outside the brackets. In our sample code, both the key and the value have the type string.

In the upcoming practice tasks, we will guide you through the creation, access, and manipulation of elements within maps, ensuring you are equipped to harness the capabilities of Go.

Adding a New Value to a Map

To add a new value to a map, you simply assign a value to a new key. If the key doesn't already exist in the map, it will be added.

// Initializing the map
capitalCities := map[string]string{
    "France": "Paris",
    "Japan": "Tokyo",
    "Kenya": "Nairobi",
}

// Adding a new key-value pair
capitalCities["Germany"] = "Berlin"

Accessing a Specific Value with a Key

You can access a specific value in a map using its key. If the key exists, you'll get the corresponding value.

// Accessing the value associated with the key "Japan"
capital := capitalCities["Japan"]
fmt.Println("The capital of Japan is:", capital)  // Output: The capital of Japan is: Tokyo

Updating an Existing Value

To update an existing value in a map, use the key to assign a new value.

// Updating the capital of France
capitalCities["France"] = "Marseille"

// Verify the update
fmt.Println("The updated capital of France is:", capitalCities["France"])  // Output: The updated capital of France is: Marseille
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal