Introduction to Maps in Go

Introduction to Maps in Go

Hi, and welcome! Today, we'll explore Maps, a data structure that organizes data into key-value pairs, much like a treasure box with unique labels for each compartment.

Imagine dozens of toys in a box. If each toy had a unique label (the key), you could directly select a toy (the value) using the label. No rummaging required — that's the power of Maps. Today, we'll understand Maps and learn how to implement them in Go.

Understanding Maps in Go

Maps are special data structures that use unique keys instead of indices. Think of them as arrays where the indices can be of any comparable type.

Go provides the map data type to implement this functionality. Maps hold data in key-value pairs.

Let's create a map, functioning as a catalog for a library:

package main

import "fmt"

func main() {
    // Creating a catalog for the library using map with initialization
    libraryCatalog := map[string]string{
        "book1": "A Tale of Two Cities",
        "book2": "To Kill a Mockingbird",
        "book3": "1984",
    }
    
    fmt.Println(libraryCatalog)
}

In this map, "book1", "book2", and "book3" are keys, while the book titles serve as their respective values.

It's important to remember that the keys should be of any type that is comparable. Examples include string, int, and float64. The values can be of any type.

Map Operations: Accessing, Updating, and Removing Elements

Maps allow you to access, update, or remove elements:

  1. Accessing Elements: You can retrieve a book's title using its key: libraryCatalog["book1"] would return "A Tale of Two Cities." If you try to access a key that isn't present in the map, it will return the zero value for the value's type. To check for key existence, use the second return value from the map access.

    package main
    
    import "fmt"
    
    func main() {
        // Creating a catalog for the library using map with initialization
        libraryCatalog := map[string]string{
            "book1": "A Tale of Two Cities",
            "book2": "To Kill a Mockingbird",
            "book3": "1984",
        }
    
        // Accessing a book's title
        if title1, exists := libraryCatalog["book1"]; exists {
            fmt.Println(title1) // Output: "A Tale of Two Cities"
        } else {
            fmt.Println("Key not found")
        }
    
        // Accessing a nonexistent key
        if titleNonexistent, exists := libraryCatalog["book100"]; exists {
            fmt.Println(titleNonexistent)
        } else {
            fmt.Println("Key not found") // Output: "Key not found"
        }
    }
  2. Adding or Updating Elements: Add a new book or update an existing title using index notation: libraryCatalog["book4"] = "Pride and Prejudice".

    package main
    
    import "fmt"
    
    func main() {
        // Creating a catalog for the library using map with initialization
        libraryCatalog := map[string]string{
            "book1": "A Tale of Two Cities",
            "book2": "To Kill a Mockingbird",
            "book3": "1984",
        }
    
        // Updating an existing book's title
        libraryCatalog["book1"] = "The Tell-Tale Heart"
        fmt.Println("Updated book1:", libraryCatalog["book1"]) // Output: "Updated book1: The Tell-Tale Heart"
    
        // Adding a new book to the catalog
        libraryCatalog["book4"] = "Pride and Prejudice"
        fmt.Println("Added book4:", libraryCatalog["book4"]) // Output: "Added book4: Pride and Prejudice"
    }
  3. Removing Elements: If book1 no longer exists in our library, remove it using delete(libraryCatalog, "book1").

    package main
    
    import "fmt"
    
    func main() {
        // Creating a catalog for the library using map with initialization
        libraryCatalog := map[string]string{
            "book1": "A Tale of Two Cities",
            "book2": "To Kill a Mockingbird",
            "book3": "1984",
        }
    
        // Removing an existing book from the catalog
        delete(libraryCatalog, "book1")
        if _, exists := libraryCatalog["book1"]; !exists {
            fmt.Println("Removed book1: null") // Output: "Removed book1: null"
        }
    }
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