Lesson 8 of 18

Maps

Key-Value Storage

Maps are Go's built-in hash table. They store key-value pairs and provide constant-time lookups.

Creating Maps

// Map literal
ages := map[string]int{
    "Alice": 30,
    "Bob":   25,
}

// Make an empty map
scores := make(map[string]int)

The type map[string]int reads as "a map from strings to ints." Keys can be any comparable type (strings, ints, booleans, structs without slice/map fields). Values can be anything.

Like the star charts on the Enterprise, a Go map lets you look up any destination in constant time. No need to scan the entire quadrant.

Operations

m := make(map[string]int)

// Insert or update
m["alice"] = 95

// Lookup
score := m["alice"] // 95

// Delete
delete(m, "alice")

// Length
fmt.Println(len(m))

The Comma-Ok Idiom

When you look up a key that does not exist, Go returns the zero value for the value type. To distinguish between "key not found" and "key exists with zero value", use the two-value form:

value, ok := m["key"]
if ok {
    fmt.Println("found:", value)
} else {
    fmt.Println("not found")
}

This is called the "comma-ok" idiom. The second value is a boolean that indicates whether the key was present.

Iterating

Use for range to iterate over a map. The iteration order is not guaranteed. It is intentionally randomized by the runtime:

for key, value := range m {
    fmt.Printf("%s: %d\n", key, value)
}

Your Task

Write a function wordCount that takes a string and returns a map[string]int where each key is a word and each value is how many times that word appears.

Use strings.Fields to split the string into words (it splits on whitespace).

Go runtime loading...
Loading...
Click "Run" to execute your code.