Map
A map is a data structure that manages key-value pairs. It is equivalent to a "dictionary" or "hash table" in other languages, and allows you to quickly retrieve a value by its key.
Syntax
// Declaring and initializing a map
var m map[KeyType]ValueType // nil map (read-only)
m := make(map[KeyType]ValueType) // writable map
m := map[KeyType]ValueType{ // initialized with a literal
key1: value1,
key2: value2,
}
// Operations
m[key] = value // add or update
value := m[key] // retrieve (zero value if key not found)
value, ok := m[key] // check if key exists
delete(m, key) // delete
length := len(m) // number of elements
Syntax Reference
| Operation | Description |
|---|---|
| make(map[K]V) | Creates an empty map. Writing to a nil map causes a panic, so always initialize with make or a literal. |
| m[key] = val | Sets a value for the given key. If the key already exists, its value is overwritten. |
| val := m[key] | Retrieves the value for the given key. If the key does not exist, the zero value for the value type is returned. |
| val, ok := m[key] | Retrieves the value and checks whether the key exists at the same time. ok is true if the key exists, false otherwise. |
| delete(m, key) | Removes the specified key and its value from the map. No error occurs if the key does not exist. |
| len(m) | Returns the number of elements in the map. |
Sample Code
package main
import "fmt"
func main() {
// Create a map with make
scores := make(map[string]int)
scores["Tanaka"] = 85
scores["Suzuki"] = 92
scores["Sato"] = 78
fmt.Println(scores["Tanaka"]) // 85
// Initialize with a literal
colors := map[string]string{
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF",
}
// Check if a key exists
if val, ok := colors["red"]; ok {
fmt.Println("red:", val)
}
// Non-existent key (returns zero value)
fmt.Println(scores["Yamada"]) // 0
// Delete an entry
delete(scores, "Sato")
fmt.Println(len(scores)) // 2
// Loop with range (order is not guaranteed)
for name, score := range scores {
fmt.Printf("%s: %d\n", name, score)
}
}
Notes
Maps are reference types. Passing a map to a function or assigning it to another variable makes both point to the same underlying map. Declaring a map with just 'var m map[string]int' creates a nil map, and attempting to write to it will cause a panic. Always initialize a map with 'make()' or a map literal before use.
Only types that support the equality operator ('==') can be used as map keys. Slices, other maps, and function types cannot be used as keys.
The iteration order of a map is intentionally randomized by Go's specification and may differ on each run. If you need a consistent order, extract the keys into a slice and sort them first.
If you find any errors or copyright issues, please contact us.