0
0
Goprogramming~5 mins

Map use cases in Go

Choose your learning style9 modes available
Introduction
Maps help you store and find data quickly using keys, like a real-life dictionary.
When you want to count how many times words appear in a text.
When you need to look up a phone number by a person's name.
When you want to group items by categories, like sorting fruits by color.
When you want to check if something exists in a collection without searching all items.
Syntax
Go
var m map[keyType]valueType
m = make(map[keyType]valueType)
m[key] = value
value = m[key]
delete(m, key)
Maps use keys to find values quickly, like a label on a box.
You must create a map with make() before adding items.
Examples
Create a map with string keys and int values, add an item, then print it.
Go
m := make(map[string]int)
m["apple"] = 5
fmt.Println(m["apple"])
Create and fill a map in one line, then get a value by key.
Go
m := map[int]string{1: "one", 2: "two"}
fmt.Println(m[2])
Check if a key exists before using its value.
Go
m := make(map[string]int)
value, ok := m["banana"]
if ok {
    fmt.Println("Found", value)
} else {
    fmt.Println("Not found")
}
Sample Program
This program shows how to create a map, add items, check for a key, and delete an item.
Go
package main

import "fmt"

func main() {
    // Create a map to count fruits
    fruitCount := make(map[string]int)

    // Add some fruits
    fruitCount["apple"] = 3
    fruitCount["banana"] = 2
    fruitCount["orange"] = 5

    // Print counts
    fmt.Println("Apple count:", fruitCount["apple"])
    fmt.Println("Banana count:", fruitCount["banana"])

    // Check if "grape" exists
    if count, ok := fruitCount["grape"]; ok {
        fmt.Println("Grape count:", count)
    } else {
        fmt.Println("Grape not found")
    }

    // Remove "banana"
    delete(fruitCount, "banana")

    // Print map after deletion
    fmt.Println("After deleting banana:", fruitCount)
}
OutputSuccess
Important Notes
Maps do not keep order of items; the order when you print may change.
Accessing a key that does not exist returns the zero value for the value type.
Use the second value when accessing a map to check if the key exists.
Summary
Maps store data with keys for fast lookup.
Create maps with make() before use.
Check if a key exists to avoid errors.