0
0
GoHow-ToBeginner · 3 min read

How to Create Map in Go: Syntax and Examples

In Go, you create a map using the make function or a map literal with the syntax map[keyType]valueType. Maps store key-value pairs and are useful for fast lookups by keys.
📐

Syntax

A map in Go is declared with the syntax map[keyType]valueType. You can create a map using make or a map literal.

  • map[keyType]valueType: Defines the type of keys and values.
  • make(map[keyType]valueType): Creates an empty map ready to use.
  • map literal: Creates a map with initial key-value pairs.
go
var m map[string]int
m = make(map[string]int)

// or using a map literal
m2 := map[string]int{"apple": 5, "banana": 3}
💻

Example

This example shows how to create a map, add key-value pairs, retrieve a value, and check if a key exists.

go
package main

import "fmt"

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

    // Add key-value pairs
    fruits["apple"] = 10
    fruits["banana"] = 5

    // Retrieve a value
    fmt.Println("Apple count:", fruits["apple"])

    // Check if a key exists
    count, ok := fruits["orange"]
    if ok {
        fmt.Println("Orange count:", count)
    } else {
        fmt.Println("Orange not found")
    }
}
Output
Apple count: 10 Orange not found
⚠️

Common Pitfalls

Common mistakes when working with maps in Go include:

  • Using a nil map without initializing it with make, which causes a runtime panic when adding elements.
  • Not checking if a key exists before using its value, which can lead to unexpected zero values.
  • Assuming map iteration order is fixed; Go randomizes it.
go
package main

import "fmt"

func main() {
    var m map[string]int // m is nil
    // m["key"] = 1 // This will panic: assignment to entry in nil map

    m = make(map[string]int) // Correct initialization
    m["key"] = 1
    fmt.Println(m["key"])

    // Checking key existence
    val, ok := m["missing"]
    if ok {
        fmt.Println("Value:", val)
    } else {
        fmt.Println("Key not found")
    }
}
Output
1 Key not found
📊

Quick Reference

OperationSyntaxDescription
Declare map variablevar m map[string]intDeclares a map variable, initially nil
Create mapm = make(map[string]int)Initializes an empty map
Create with valuesm := map[string]int{"a":1, "b":2}Creates map with initial key-value pairs
Add or updatem["key"] = valueSets value for a key
Retrieve valueval := m["key"]Gets value for a key (zero if missing)
Check key existsval, ok := m["key"]Checks if key is present
Delete keydelete(m, "key")Removes key from map

Key Takeaways

Use make(map[keyType]valueType) to create a usable map before adding elements.
Maps store key-value pairs and allow fast lookups by key.
Always check if a key exists to avoid confusion with zero values.
Map iteration order is random and should not be relied upon.
Use map literals to create maps with initial data quickly.