Map Declaration
Maps in Go are similar to dictionaries in Python. To declare a map, use the following syntax:
var mapVariable map[keyType]valueType
In this declaration:
keyTypedefines the data type of keysvalueTypedefines the data type of corresponding values
By default, map variables are initialized to nil. Memory allocation requires the make() function:
make(map[keyType]valueType, [capacity])
Attempting to assign values to an uninitialized map will result in a runtime panic:
package main
import "fmt"
func main() {
var uninitializedMap map[string]string
uninitializedMap["key"] = "value" // This causes panic
fmt.Println(uninitializedMap)
}
Value Assignment
Assign values using key-value pairs:
myMap["identifier"] = "data"
Element Removal
Use the built-in delete() function to remove elements:
delete(targetMap, "identifier")
If the specified key doesn't exist, the operation has no effect. However, calling delete() on a nil map will cause a panic.
Key Eixstence Check
Go provides a special syntax to verify if a key exists in a map:
value, exists := mapVariable[key]
if exists {
// Key found
} else {
// Key not found
}
Map Iteration
Iterate through maps using the range keyword:
func main() {
grades := make(map[string]int)
grades["Alice"] = 85
grades["Bob"] = 92
grades["Charlie"] = 78
for name, score := range grades {
fmt.Println(name, score)
}
}
To iterate only over keys:
func main() {
grades := make(map[string]int)
grades["Alice"] = 85
grades["Bob"] = 92
grades["Charlie"] = 78
for name := range grades {
fmt.Println(name)
}
}
Ordered Map Traversal
For sorted iteration, extract keys into a slice and sort them:
func main() {
rand.Seed(time.Now().UnixNano())
records := make(map[string]int, 100)
for i := 0; i < 50; i++ {
id := fmt.Sprintf("record%02d", i)
records[id] = rand.Intn(100)
}
keys := make([]string, 0, len(records))
for key := range records {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
fmt.Println(key, records[key])
}
}
Complete Example
This example demonstrates comprehensive map usage:
package main
import "fmt"
type Employee struct {
ID string
Name string
Department string
}
func main() {
employees := make(map[string]Employee)
employees["E001"] = Employee{"E001", "John Smith", "Engineering"}
employees["E002"] = Employee{"E002", "Jane Doe", "Marketing"}
employees["E003"] = Employee{"E003", "Bob Johnson", "Sales"}
if emp, found := employees["E001"]; found {
fmt.Printf("Employee Found: %s, %s, %s\n", emp.ID, emp.Name, emp.Department)
} else {
fmt.Println("Employee not found")
}
}