Introduction and Goal Setting

Hello there! In this lesson, we will apply maps to real-world challenges. Our focus will be on solving tasks such as cataloging books in a library, counting votes in an election, and tracking inventories.

Real-World Scenarios Calling for Maps

Maps are beneficial in real-life applications, such as the ones mentioned above, due to their ability to rapidly retrieve data with unique keys and efficiently handle larger datasets. Let's understand their efficiency with some actual examples.

Solving Real-World Task 1: Cataloging Books in a Library

Suppose you're asked to manage the cataloging of books in a library. Here, the book ID serves as the key, while the details of the book, such as the title, author, and year of publication, are stored as values.

This approach allows us to add, search for, and remove books from our library catalog using Go's maps.

package main

import "fmt"

func main() {
    // Initializing a map with nested maps
    libraryCatalog := make(map[string]map[string]string)

    // Details of a book
    bookId := "123"
    // Creating a map to store details of the book
    bookDetails := map[string]string{
        "title":           "To Kill a Mockingbird",
        "author":          "Harper Lee",
        "year_published": "1960",
    }

    libraryCatalog[bookId] = bookDetails // Adding a book to library catalog

    // Searching for a book
    if details, ok := libraryCatalog[bookId]; ok {
        fmt.Printf("Title: %s, Author: %s, Year Published: %s\n",
            details["title"], details["author"], details["year_published"])
    }

    // Removing a book from the library
    delete(libraryCatalog, bookId)
}

make() is a built-in Go function used to initialize maps, slices, and channels. For example, libraryCatalog := make(map[string]map[string]string) initializes an empty map where string keys map to nested maps, ready for storing key-value pairs.

As you can see, maps make the task of cataloging books in the library simpler and more efficient!

Solving Real-World Task 2: Counting Votes in an Election

Imagine a scenario in which we need to count votes in an election. We employ a map, where each name is a unique key, and the frequency of that name serves as the associated value. Let's write some Go code to better understand this.

package main

import "fmt"

func main() {
    // Cast votes
    votesList := []string{"Alice", "Bob", "Alice", "Charlie", "Bob", "Alice"}

    // Initializing a map
    voteCounts := make(map[string]int)

    // Counting the votes
    for _, name := range votesList {
        voteCounts[name]++
    }

    for name, count := range voteCounts {
        fmt.Printf("%s: %d\n", name, count)
    }
    // Prints: Alice: 3, Bob: 2, Charlie: 1
}

Maps facilitate the efficient counting of votes.

Solving Real-World Task 3: Tracking Store Inventories

Finally, consider a task that involves managing a store's inventory. Here, we can use a map in which product names are keys, and quantities are values. This approach allows us to easily add new items, adjust the quantity of items, check whether an item is in stock, and much more.

package main

import "fmt"

func main() {
    // Initializing an inventory
    storeInventory := map[string]int{
        "Apples":  100,
        "Bananas": 80,
        "Oranges": 90,
    }

    // Adding a new product to inventory and setting its quantity
    storeInventory["Pears"] = 50

    // Updating the number of apples in inventory
    if _, ok := storeInventory["Apples"]; ok {
        storeInventory["Apples"] += 20
    }

    // A product to be checked
    prod := "Apples"
    fmt.Printf("Total %s in stock: %d\n", prod, storeInventory[prod])

    // Check if a product is in stock
    prod = "Mangoes"
    if _, ok := storeInventory[prod]; ok {
        fmt.Printf("%s are in stock.\n", prod) // If mangoes exist in inventory
    } else {
        fmt.Printf("%s are out of stock.\n", prod) // If mangoes don't exist in inventory
    }
}

Thus, when managing inventory data, maps offer an efficient solution!

Lesson Summary and Practice

In this lesson, we bridged the gap between the theory of maps and their practical applications. We explored real-world problems that can be solved using maps and implemented Go code to address them.

Now, get ready for hands-on practice exercises that will help reinforce these concepts and hone your map problem-solving skills. Happy coding!

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