Start learning free

LESSON 125 OF 671 · DICTIONARIES

Dictionaries (map) in Go

Lesson

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.

STEP 1 OF 1
    Ctrl + Enter to check