0
0
Goprogramming~5 mins

Map creation in Go

Choose your learning style9 modes available
Introduction

A map in Go helps you store pairs of keys and values. It is like a real-life dictionary where you look up a word (key) to find its meaning (value).

When you want to quickly find a value using a unique key, like looking up a phone number by a person's name.
When you need to count how many times each word appears in a text.
When you want to store settings or options with names and values.
When you want to group data by categories, like storing students by their class.
Syntax
Go
var mapName map[keyType]valueType
mapName = make(map[keyType]valueType)

// Or combined:
mapName := make(map[keyType]valueType)

You must use make to create a map before adding items.

Keys must be a type that can be compared, like strings or integers.

Examples
This creates a map named ages where keys are strings and values are integers.
Go
var ages map[string]int
ages = make(map[string]int)
This creates and initializes a map named scores with string keys and float64 values.
Go
scores := make(map[string]float64)
This creates a map with initial key-value pairs for colors and their hex codes.
Go
colors := map[string]string{"red": "#ff0000", "green": "#00ff00"}
Sample Program

This program creates a map to store ages by name, adds two entries, and prints the map and one value.

Go
package main

import "fmt"

func main() {
    // Create a map to store ages
    ages := make(map[string]int)

    // Add some data
    ages["Alice"] = 30
    ages["Bob"] = 25

    // Print the map
    fmt.Println("Ages:", ages)

    // Access a value
    fmt.Println("Alice's age:", ages["Alice"])
}
OutputSuccess
Important Notes

If you try to read a key that does not exist, Go returns the zero value for the value type (like 0 for int).

You can check if a key exists using the comma-ok idiom: value, ok := mapName[key].

Summary

Maps store key-value pairs for fast lookup.

Create maps with make before use.

Keys must be comparable types like strings or ints.