Level: BeginnerGo Programs

Go Map Programs with Output: Count, Group, Merge and Sort

Updated 18 min read
Go Map Programs featured image: word count, groups and merged settings

Go map programs store data as key-value pairs, such as a product code and its price or a word and how often it appears. Maps give you fast lookups by key, so they power counters, caches, groups and indexes in almost every Go service. In this post, you will write fourteen map programs with their exact output, and then practice the map questions that trip up many Go developers.

We already used small maps in our Go string manipulation programs and Go searching programs. For the theory behind maps, read Go maps explained with examples. All programs were tested on Go 1.27.

What are Go Map Programs?

Go map programs use the built-in map[K]V type, where every key of type K points to one value of type V. Keys are unique, so writing to an existing key replaces its value.

Think of a phone contact list. You look up “Asha” and get her number straight away, without reading every contact. A map works the same way: give it a key, and it finds the value almost instantly.

Why Go Map Programs Matter

Maps solve a huge range of everyday problems. For example, you count page views per URL, cache API results by user ID and group orders by city. Interviewers use Go map programs to test frequency counting, grouping and your knowledge of map rules like random order.

  • Counting: word counts, vote counts and visitor counts.
  • Grouping: students by grade, orders by status, files by type.
  • Lookups: config values, caches and ID to name tables.

How Go Map Programs Work

A map hashes each key to decide where to store its value. When you read m[key], Go hashes the key again and jumps straight to the right slot. That is why lookups take about the same time whether the map holds ten items or ten million.

Go map programs diagram showing keys hashed into buckets that hold values
Go hashes each key to find its bucket, so reading and writing by key is fast.

The table below lists the map operations you will use in Go map programs.

OperationSyntaxNotes
Createm := map[string]int{}Or make(map[string]int)
Add or updatem[“pen”] = 40Replaces an old value
Readv := m[“pen”]Missing key gives zero value
Check keyv, ok := m[“pen”]ok is false if missing
Deletedelete(m, “pen”)Safe if key is missing
Lengthlen(m)Number of keys
Remove allclear(m)Since Go 1.21

Basic Go Map Programs

These first Go map programs cover the core actions on a map. If maps are new to you, start with Program 1.

Program 1: Your First Map of Fruit Prices

This is the smallest useful map. Each fruit name points to its price.

package main

import "fmt"

func main() {
    // Step 1: create a map. Each fruit name (string) points to a price (int).
    prices := map[string]int{ // := creates the variable and sets its value
        "apple":  120,
        "banana": 40,
    }

    // Step 2: add a new fruit with its price.
    prices["mango"] = 150

    // Step 3: read values by their key.
    fmt.Println("Apple costs", prices["apple"])
    fmt.Println("Mango costs", prices["mango"])

    // len tells you how many keys the map holds.
    fmt.Println("Fruits in the map:", len(prices))
}
Apple costs 120
Mango costs 150
Fruits in the map: 3

First, we create the map with two fruits inside curly braces. Then prices["mango"] = 150 adds a third fruit. To read a price, you put the key in square brackets, like prices["apple"]. Finally, len counts the keys, which gives 3.

Program 2: Add, Update, Read and Delete

package main

import "fmt"

func main() {
    // Step 1: start with two items in stock.
    stock := map[string]int{"pen": 40, "book": 12}

    // Step 2: change the map.
    stock["bag"] = 5      // add a new key
    stock["pen"] = 35     // the key already exists, so this updates it
    delete(stock, "book") // remove the key "book"

    // Step 3: read the values. "book" is gone, so it reads as 0.
    fmt.Println(stock["pen"], stock["bag"], stock["book"])
    fmt.Println(len(stock))
}
35 5 0
2

Writing to a new key adds it, and writing to an old key replaces its value. The built-in delete function removes a key. Reading the deleted key “book” gives 0, the zero value for int. It does not cause an error.

Program 3: Check if a Key Exists

package main

import "fmt"

func main() {
    // Coffee is free here, so its price is 0.
    prices := map[string]float64{"tea": 15, "coffee": 0}
    items := []string{"tea", "coffee", "juice"}

    for _, item := range items { // range gives each index (ignored with _) and item
        // ok is true if the key was found in the map, false if not.
        price, ok := prices[item]
        if ok {
            fmt.Printf("%s costs %.0f\n", item, price) // %.0f prints a number with no decimals
        } else {
            fmt.Printf("%s is not on the menu\n", item)
        }
    }
}
tea costs 15
coffee costs 0
juice is not on the menu

Reading a map can give back two values. The first is the price, and the second, ok, says if the key exists. The ok flag is the only way to tell “coffee costs 0” from “juice does not exist”. Use this form whenever zero is a valid value.

Program 4: Print a Map in Sorted Key Order

Map order is random in Go, on purpose. To print in order, sort the keys first.

package main

import (
    "fmt"
    "maps"
    "slices"
)

func main() {
    ages := map[string]int{"Ravi": 30, "Asha": 25, "Meera": 28, "Kiran": 35}

    // Step 1: get all the keys and sort them A to Z.
    names := slices.Sorted(maps.Keys(ages)) // maps.Keys gives the keys, slices.Sorted sorts them

    // Step 2: print each name with its age, in sorted order.
    for _, name := range names {
        fmt.Println(name, ages[name])
    }
}
Asha 25
Kiran 35
Meera 28
Ravi 30

maps.Keys hands out every key of the map, and slices.Sorted collects them into a sorted slice. Then the loop walks that sorted slice and looks up each age. Because the names are sorted, the output is the same on every run.

Counting and Grouping Go Map Programs

These Go map programs count items and sort them into groups.

Program 5: Count Votes for Each Color

Counting is the most common job for a map. Here is the easiest version.

package main

import "fmt"

func main() {
    votes := []string{"red", "blue", "red", "green", "red", "blue"}

    // An empty map: color -> number of votes.
    count := map[string]int{}

    // Add one vote for each color we see.
    for _, color := range votes {
        count[color]++ // a missing key starts at 0, so the first ++ makes it 1
    }

    fmt.Println("red:", count["red"])
    fmt.Println("blue:", count["blue"])
    fmt.Println("green:", count["green"])
}
red: 3
blue: 2
green: 1

The loop reads one vote at a time. When a color is new, its count starts at 0, so count[color]++ makes it 1. When the color comes again, the same line adds one more. You never need to set up each color first.

Program 6: Top Three Words by Count

package main

import (
    "fmt"
    "maps"
    "slices"
    "strings"
)

func main() {
    text := "go is fun and go is fast and go is easy to learn"

    // Step 1: count how often each word appears.
    count := map[string]int{}
    for _, word := range strings.Fields(text) { // strings.Fields splits the text on spaces
        count[word]++
    }

    // Step 2: put all the words into a slice so we can sort them.
    words := slices.Collect(maps.Keys(count))

    // Step 3: sort by count (high to low), then by word (A to Z) for ties.
    slices.SortFunc(words, func(first, second string) int {
        if count[first] != count[second] {
            return count[second] - count[first] // a negative result puts first before second
        }
        return strings.Compare(first, second)
    })

    // Step 4: print the first three words. words[:3] means items 0, 1 and 2.
    for _, word := range words[:3] {
        fmt.Println(word, count[word])
    }
}
go 3
is 3
and 2

First, we count every word, just like the votes in Program 5. Next, we copy the words into a slice and sort it with a small compare function. A higher count comes first, and equal counts fall back to A to Z order. Without that tie-breaker, “go” and “is” could swap places between runs.

Program 7: Group Students by Grade

A map of slices groups many values under one key.

package main

import (
    "fmt"
    "maps"
    "slices"
)

// gradeFor turns a mark into a letter grade.
func gradeFor(mark int) string {
    if mark >= 90 {
        return "A"
    } else if mark >= 75 {
        return "B"
    }
    return "C"
}

func main() {
    marks := map[string]int{"Asha": 91, "Ravi": 76, "Meera": 88, "Kiran": 64, "Dev": 95}

    // Each grade (key) holds a list of student names (value).
    groups := map[string][]string{}

    // Step 1: visit students in A to Z order and put each one in a group.
    for _, name := range slices.Sorted(maps.Keys(marks)) {
        grade := gradeFor(marks[name])
        groups[grade] = append(groups[grade], name) // append adds the name to the end of the list
    }

    // Step 2: print the groups in order A, B, C.
    for _, grade := range slices.Sorted(maps.Keys(groups)) {
        fmt.Println(grade, groups[grade])
    }
}
A [Asha Dev]
B [Meera Ravi]
C [Kiran]

The helper gradeFor turns each mark into a letter. Then append adds the student’s name to the list for that letter. append works on a missing key, because reading it gives a nil (empty) slice. So we never need to create each group first.

Program 8: Invert a Map

package main

import (
    "fmt"
    "maps"
    "slices"
)

func main() {
    codes := map[string]string{"IN": "India", "JP": "Japan", "FR": "France"}

    // Step 1: build a new map that goes the other way, name -> code.
    byName := map[string]string{}
    for code, name := range codes { // range on a map gives each key and value
        byName[name] = code
    }

    // Step 2: print the new map in sorted order.
    for _, name := range slices.Sorted(maps.Keys(byName)) {
        fmt.Println(name, "->", byName[name])
    }
}
France -> FR
India -> IN
Japan -> JP

The loop takes each code and name pair and stores it the other way round. So the country name becomes the key, and the code becomes the value. This works only when values are unique. If two keys share a value, one of them is lost in the inverted map.

Special Go Map Programs

These Go map programs show patterns that you will use in real projects.

Program 9: A Set with map[string]struct{}

Go has no set type, so we use a map with empty struct values, which take no memory.

package main

import "fmt"

func main() {
    // The value struct{} is empty. We only care about the keys.
    visited := map[string]struct{}{}
    pages := []string{"/home", "/about", "/home", "/blog", "/about"}

    // Step 1: add every page. A repeated page just overwrites itself.
    for _, page := range pages {
        visited[page] = struct{}{} // struct{}{} is the one empty value
    }

    // Step 2: check if "/blog" is in the set. We ignore the value with _.
    _, seen := visited["/blog"]
    fmt.Println(len(visited), seen)
}
3 true

Keys in a map are unique, so the repeated pages are stored only once. That leaves 3 pages in the set. To check if a page is there, read it with the two-value form and keep only the second value.

Program 10: Merge Two Maps

package main

import (
    "fmt"
    "maps"
    "slices"
)

func main() {
    defaults := map[string]string{"theme": "light", "lang": "en", "size": "M"}
    user := map[string]string{"theme": "dark", "size": "L"}

    // Step 1: make a full copy, so defaults stays unchanged.
    settings := maps.Clone(defaults)

    // Step 2: copy the user's values on top. Matching keys are replaced.
    maps.Copy(settings, user)

    // Step 3: print the merged settings in sorted order.
    for _, key := range slices.Sorted(maps.Keys(settings)) {
        fmt.Println(key, settings[key])
    }
}
lang en
size L
theme dark

maps.Clone gives us a new map with the same keys and values. Then maps.Copy writes every user setting into it, so “theme” and “size” change. The key “lang” was not in the user map, so it keeps the default value.

Program 11: Map with Struct Values

You cannot change a field of a struct inside a map directly. Read it, change it, and write it back.

package main

import "fmt"

// Account holds an owner's name and their money.
type Account struct {
    Owner   string
    Balance int
}

func main() {
    // Way 1: the map stores full Account values.
    accounts := map[int]Account{101: {"Asha", 5000}}
    account := accounts[101]  // Step 1: copy the value out
    account.Balance += 1500   // Step 2: change the copy
    accounts[101] = account   // Step 3: store it back
    fmt.Println(accounts[101])

    // Way 2: the map stores pointers (*Account), which are addresses of accounts.
    accountPointers := map[int]*Account{102: {"Ravi", 2000}}
    accountPointers[102].Balance -= 500 // a pointer lets you change the struct in place
    fmt.Println(*accountPointers[102])  // * reads the struct the pointer points to
}
{Asha 6500}
{Ravi 1500}

In the first way, reading accounts[101] gives you a copy. So you change the copy and then store it back in the map. In the second way, the map holds addresses, so you can change the struct directly. Choose the style that fits how often you update.

Program 12: Nested Map for City Sales

package main

import "fmt"

// addSale adds a quantity for one product in one city.
func addSale(sales map[string]map[string]int, city, product string, quantity int) {
    // Step 1: create the inner map for this city if it does not exist yet.
    if sales[city] == nil { // nil means "no map here yet"
        sales[city] = map[string]int{}
    }
    // Step 2: add the quantity to the product total.
    sales[city][product] += quantity
}

func main() {
    // Outer key: city. Inner key: product. Value: quantity sold.
    sales := map[string]map[string]int{}
    addSale(sales, "Pune", "pen", 10)
    addSale(sales, "Pune", "pen", 5)
    addSale(sales, "Delhi", "bag", 3)
    fmt.Println(sales["Pune"]["pen"], sales["Delhi"]["bag"], sales["Goa"]["pen"])
}
15 3 0

Each city points to its own small map of products. The helper addSale first makes sure that inner map exists, then adds the quantity. Reading a missing city like “Goa” is safe and gives 0. Writing to a nil inner map, however, would panic.

Program 13: Delete While Iterating

package main

import (
    "fmt"
    "maps"
    "slices"
)

func main() {
    carts := map[string]int{"u1": 0, "u2": 3, "u3": 0, "u4": 1}

    // Way 1: delete empty carts inside a normal range loop.
    for user, items := range carts {
        if items == 0 {
            delete(carts, user) // deleting during range is safe in Go
        }
    }
    fmt.Println(slices.Sorted(maps.Keys(carts)))

    // Way 2: maps.DeleteFunc removes every key where the function returns true.
    maps.DeleteFunc(carts, func(user string, items int) bool {
        return items < 2
    })
    fmt.Println(carts)
}
[u2 u4]
map[u2:3]

The first loop removes users u1 and u3, because their carts are empty. Go allows deleting keys during a range loop. maps.DeleteFunc does the same job with a small test function. Here it removes u4, because 1 item is less than 2.

Program 14: Compare Two Maps

package main

import (
    "fmt"
    "maps"
)

func main() {
    first := map[string]int{"x": 1, "y": 2}
    second := map[string]int{"y": 2, "x": 1} // same data, different writing order
    third := map[string]int{"x": 1}

    // maps.Equal is true only if both maps have the same keys and values.
    fmt.Println(maps.Equal(first, second), maps.Equal(first, third))
}
true false

The first two maps hold the same pairs, so they are equal even though we wrote them in a different order. The third map is missing “y”, so it is not equal. Maps cannot use ==, except to compare with nil. maps.Equal checks the keys and values for you.

Map vs Slice in Go Map Programs

Maps and slices both hold many values, but they suit different jobs. The diagram and table below compare them.

Go map programs comparison of maps and slices
Use a map for fast lookups by key, and a slice when order matters or you loop over every item.
FeatureMapSlice
Find byKeyIndex
Lookup speedO(1) averageO(n) unless sorted
OrderRandomKept
DuplicatesKeys are uniqueAllowed
Zero value usableRead yes, write noYes, append works

In short, pick a map for lookups, counts and groups. Pick a slice for ordered lists and when you visit every item.

Common Mistakes in Go Map Programs

  • Writing to a nil map: var m map[string]int then m["a"] = 1 panics. Create it with make or {} first.
  • Relying on order: map order changes between runs, so sort keys before printing.
  • Missing the ok flag: a zero value does not prove the key exists.
  • Changing struct fields in place: m[k].Field = v does not compile with struct values.
  • Sharing a map across goroutines: plain maps are not safe for concurrent writes. Use a mutex or sync.Map.

Best Practices for Go Map Programs

  • Use make with a size hint when you know roughly how many keys you will add.
  • Sort keys for output, so logs and tests are stable.
  • Use map[K]struct{} for sets, which saves memory.
  • Clone before changing maps you received from other code.
  • Use the maps package for Keys, Values, Clone, Copy, Equal and DeleteFunc.

Go Map Programs Interview Questions and Answers

Interviewers use short Go map programs to test the special rules of maps. Each program is complete, with real output from Go 1.27.

Go Map Programs Rule Questions

Q1. What happens when you write to a nil map?

package main

func main() {
    var scores map[string]int // declared but never created, so it is nil
    scores["a"] = 1           // writing to a nil map panics
}
panic: assignment to entry in nil map

A nil map has no storage. Reading from it is fine and returns zero values, but writing panics.

Q2. What does this program print?

package main

import "fmt"

func main() {
    var scores map[string]int // a nil map

    // Reading a nil map gives the zero value, and len is 0.
    fmt.Println(scores["x"], len(scores), scores == nil)

    // A range loop over a nil map simply runs zero times.
    for key := range scores {
        fmt.Println(key)
    }

    // delete on a nil map does nothing.
    delete(scores, "x")
    fmt.Println("ok")
}
0 0 true
ok

Reading, ranging and deleting are all safe on a nil map. Only writing causes a panic.

Q3. Why does this program not compile?

package main

// Point is a spot with X and Y positions.
type Point struct{ X, Y int }

func main() {
    points := map[string]Point{"a": {1, 2}}
    points["a"].X = 10 // not allowed: you cannot change a field inside a map
}
cannot assign to struct field points["a"].X in map

Map values are not addressable, because Go may move them when the map grows. Copy the struct out, change it, and store it back, or use pointer values.

Q4. Which types can be map keys?

Any comparable type: numbers, strings, bools, pointers, channels, arrays and structs made of comparable fields. Slices, maps and functions cannot be keys.

Behaviour Questions

Q5. What does this program print?

package main

import "fmt"

// addItem writes one new key into the map it receives.
func addItem(items map[string]int) {
    items["new"] = 1
}

func main() {
    items := map[string]int{}
    addItem(items)
    fmt.Println(items, len(items))
}
map[new:1] 1

A map value is a small handle to the real data. So a function that writes to the map changes the caller’s map too.

Q6. Is map order random every time?

Yes, by design. Go randomises the starting point of each range loop, so code never depends on order by accident. fmt.Println of a map is the one exception, because it sorts keys for printing.

package main

import "fmt"

func main() {
    letters := map[string]int{"b": 2, "c": 3, "a": 1}
    fmt.Println(letters) // fmt sorts map keys before printing
}
map[a:1 b:2 c:3]

Q7. What does this program print?

package main

import "fmt"

func main() {
    // A rune is one character. 'l' in single quotes is a rune.
    counts := map[rune]int{}
    for _, letter := range "hello" { // range over a string gives each character
        counts[letter]++
    }
    fmt.Println(counts['l'], counts['h'], counts['z'], len(counts))
}
2 1 0 4

“hello” has four different letters, so len is 4. The missing ‘z’ simply reads as 0.

Q8. What does this program print?

package main

import "fmt"

func main() {
    original := map[string]int{"a": 1}
    other := original // this does NOT copy the map, both names share the same data
    other["a"] = 100
    fmt.Println(original["a"])
}
100

Assigning a map does not copy it. Both variables point to the same data, so use maps.Clone when you need a real copy.

Q9. What does this program print?

package main

import (
    "fmt"
    "maps"
    "slices"
)

func main() {
    letters := map[int]string{3: "c", 1: "a", 2: "b"}

    // maps.Values gives every value, and slices.Sorted sorts them.
    values := slices.Sorted(maps.Values(letters))
    fmt.Println(values)

    // clear removes every key, but the map itself still exists.
    clear(letters)
    fmt.Println(len(letters), letters == nil)
}
[a b c]
0 false

clear removes every key but keeps the map ready to use. So the map is empty, not nil.

Q10. Are Go maps safe for concurrent use?

No. If one goroutine writes while another reads or writes, the program can crash with “concurrent map writes”. Protect the map with a sync.Mutex, or use sync.Map for some special cases.

Q11. What does this program print?

package main

import "fmt"

func main() {
    // key joins a city and a year into one map key.
    type key struct {
        city string
        year int
    }
    sales := map[key]int{}
    sales[key{"Pune", 2025}] += 400
    sales[key{"Pune", 2026}] += 650
    sales[key{"Pune", 2025}] += 100 // same key as the first line, so it adds to 400
    fmt.Println(sales[key{"Pune", 2025}], len(sales))
}
500 2

A struct key lets you look up by two values at once. Here, 2025 and 2026 are separate keys, so there are 2 entries.

Q12. How do you get the number of items in a map?

Use len(m). It is O(1), because Go keeps the count as items are added and removed. There is no cap for maps.

Practice Task

This task brings several Go map programs together. Write a program that reads a list of orders as “city,amount” strings and prints the total sales per city, sorted from the highest total to the lowest. Hint: split each string with strings.Cut, convert the amount with strconv.Atoi and add it to a map[string]int.

Official Resources

Quick Recap

  • Go map programs store unique keys that each point to one value.
  • Use v, ok := m[k] to tell a missing key from a zero value.
  • Map order is random, so sort keys with slices.Sorted(maps.Keys(m)) for output.
  • Writing to a nil map panics, but reading, ranging and deleting are safe.
  • Maps are shared when assigned or passed, so clone them before changing.

What’s Next?

To finish Level 3, we combine loops and 2D slices. Read Go matrix programs with output, with matrix addition, multiplication and transpose. For more map practice, revisit Go maps explained with examples.