0
0
Goprogramming~5 mins

Why maps are used in Go

Choose your learning style9 modes available
Introduction

Maps help you store and find data quickly using keys, like looking up a phone number by a person's name.

When you want to link names to phone numbers for quick lookup.
When you need to count how many times each word appears in a text.
When you want to store settings or options by their names.
When you want to check if something exists without searching through a list.
Syntax
Go
var m map[string]int
m = make(map[string]int)
m["key"] = 10
value := m["key"]

Maps use keys to find values fast, like a dictionary.

You must create a map with make before adding items.

Examples
Store and get a color for a fruit.
Go
m := make(map[string]string)
m["apple"] = "red"
fmt.Println(m["apple"])
Create a map with initial values and get Bob's age.
Go
ages := map[string]int{"Alice": 30, "Bob": 25}
fmt.Println(ages["Bob"])
Count how many times something happens by updating the value.
Go
m := make(map[string]int)
m["count"] = 1
m["count"] += 1
fmt.Println(m["count"])
Sample Program

This program shows how to store and find phone numbers by name using a map. It also checks if a name exists before printing.

Go
package main

import "fmt"

func main() {
    // Create a map to store phone numbers by name
    phoneBook := make(map[string]string)

    // Add some entries
    phoneBook["Alice"] = "123-4567"
    phoneBook["Bob"] = "987-6543"

    // Look up a number
    fmt.Println("Alice's number:", phoneBook["Alice"])

    // Check if a name exists
    number, found := phoneBook["Charlie"]
    if found {
        fmt.Println("Charlie's number:", number)
    } else {
        fmt.Println("Charlie not found in phone book")
    }
}
OutputSuccess
Important Notes

Maps are very fast for finding data by keys compared to searching lists.

Keys in maps must be of a type that can be compared, like strings or numbers.

Maps do not keep order of items; they are for quick lookup, not sorting.

Summary

Maps store data with keys for fast lookup.

Use maps when you want to find or check data quickly by a name or label.

Always create maps with make before adding items.