Map Key Basics
Understanding Maps in Golang
In Golang, a map is a powerful data structure that allows you to store key-value pairs. Unlike arrays or slices, maps provide a way to create dynamic collections with unique keys and associated values.
Map Declaration and Initialization
There are multiple ways to create a map in Golang:
// Method 1: Using make() function
ages := make(map[string]int)
// Method 2: Map literal declaration
cities := map[string]string{
"USA": "New York",
"France": "Paris",
}
Key Characteristics
Maps in Golang have several important characteristics:
Characteristic |
Description |
Key Uniqueness |
Each key in a map must be unique |
Key Types |
Keys must be comparable types |
Value Access |
O(1) constant time complexity |
Key Type Restrictions
Not all types can be used as map keys. Valid key types must be:
- Comparable using
==
and !=
operators
- Immutable (like strings, integers)
- Cannot use slices, maps, or functions as keys
Memory Management
graph TD
A[Map Creation] --> B[Memory Allocation]
B --> C{Key-Value Pairs}
C --> D[Dynamic Resizing]
D --> E[Garbage Collection]
Maps in Golang are implemented as hash tables, providing efficient key-value storage and retrieval. LabEx recommends understanding their internal mechanics for optimal usage.
Example: Basic Map Operations
func main() {
// Creating a map
scores := map[string]int{
"Alice": 95,
"Bob": 88,
}
// Adding a new key-value pair
scores["Charlie"] = 92
// Checking key existence
value, exists := scores["Alice"]
}