In Go, a map works like a dictionary — it stores key-value pairs where each key maps to a value. Maps are a built-in type and need no extra import.
scores := map[string]int{}
scores["Alice"] = 95
scores["Bob"] = 87
scores["Charlie"] = 72
The type parameters [string]int specify the key type and value type. You can also initialize using a map literal:
ages := map[string]int{
"Alice": 25,
"Bob": 30,
}
fmt.Println(ages["Alice"]) // 25
fmt.Println(len(ages)) // 2
Assignment
Follow the Coding Tutorial and create a map named scores with three student scores!
Hint
Declare scores := map[string]int{} then use scores["Alice"] = 95 to add entries.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
