A map is an unordered collection of key-value pairs. Maps provide fast lookups, additions, and deletions based on keys. They’re similar to dictionaries in Python or objects in JavaScript.
// Map from string keys to string valuesvar dict map[string]string// Map from int keys to bool valuesvar flags map[int]bool// Map from string keys to int valuesvar scores map[string]int
A declared but uninitialized map is nil and read-only:
var dict map[string]string// Reading from a nil map returns the zero valuevalue := dict["key"]fmt.Println(value) // "" (empty string - zero value)// Length of nil map is 0fmt.Println(len(dict)) // 0// Checking if it's nilfmt.Println(dict == nil) // true
You cannot assign to a nil map - it will panic:
var dict map[string]stringdict["key"] = "value" // Panic: assignment to entry in nil map
Check if a key exists using the two-value assignment:
dict := map[string]string{ "good": "iyi", "mistake": "", // Empty string is a valid value}// Check if key existsvalue, ok := dict["good"]if ok { fmt.Printf("Found: %s\n", value) // Found: iyi}// Check for non-existent keyvalue, ok = dict["missing"]if !ok { fmt.Println("Key not found") // Key not found}// Distinguish between missing key and empty valuevalue, ok = dict["mistake"]if ok { fmt.Println("Key exists with empty value")}
Use the comma-ok idiom to distinguish between a missing key and a key with a zero value.
dict := map[string]string{ "good": "iyi", "great": "harika", "perfect": "mükemmel",}// Iterate over keys and valuesfor key, value := range dict { fmt.Printf("%q means %q\n", key, value)}// Iterate over keys onlyfor key := range dict { fmt.Println(key)}// Iterate over values onlyfor _, value := range dict { fmt.Println(value)}
Map iteration order is random! Go intentionally randomizes the iteration order. Don’t rely on any particular order.
To create an independent copy, manually copy elements:
original := map[string]int{ "a": 1, "b": 2,}// Create a new map and copy elementscopied := make(map[string]int)for k, v := range original { copied[k] = v}// Now they're independentcopied["c"] = 3fmt.Println(original) // map[a:1 b:2]fmt.Println(copied) // map[a:1 b:2 c:3]
// Use map[T]bool or map[T]struct{} for setsseen := make(map[string]bool)words := []string{"apple", "banana", "apple", "cherry"}for _, word := range words { if !seen[word] { fmt.Println("First time seeing:", word) seen[word] = true }}
cache := make(map[int]int)func fibonacci(n int) int { if n <= 1 { return n } // Check cache if val, ok := cache[n]; ok { return val } // Calculate and cache result := fibonacci(n-1) + fibonacci(n-2) cache[n] = result return result}