Tutorials / Go: From Basics to Production / Maps and working with strings

Maps and working with strings

13 min read go
Course contents (17 lessons)
  1. Getting started with Go
  2. Installing Go 1.25 and your first program
  3. Variables, types and constants
  4. Control flow: if, for and switch
  5. Functions, multiple returns and defer
  6. Slices and maps
  7. Arrays and slices
  8. Maps and working with strings
  9. Structs, methods and interfaces
  10. Structs, methods and pointers
  11. Interfaces
  12. Errors, packages and generics
  13. Error handling the Go way
  14. Packages and modules
  15. Generics
  16. Concurrency
  17. Goroutines and channels
  18. select, timeouts and context
  19. Mutexes, sync and the race detector
  20. Testing
  21. Testing and benchmarks
  22. Building and shipping a service
  23. Building an HTTP JSON API with net/http
  24. Building and deploying a Go service

Key-value lookup

A map stores values by key. In a small shop, you might map each product name to its price. The type is written map[KeyType]ValueType.

package main

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

func main() {
	prices := map[string]int{
		"tea":   120,
		"sugar": 150,
		"rice":  280,
	}

	prices["salt"] = 60       // add
	prices["tea"] = 130       // update
	delete(prices, "sugar")   // remove (no error if missing)

	// reading a missing key gives the zero value
	fmt.Println(prices["flour"]) // 0

	// the comma-ok idiom tells you whether the key exists
	if price, ok := prices["rice"]; ok {
		fmt.Println("rice costs", price)
	}
	if _, ok := prices["flour"]; !ok {
		fmt.Println("flour is not sold here")
	}

	fmt.Println(len(prices))

	// iterate in sorted key order
	for _, name := range slices.Sorted(maps.Keys(prices)) {
		fmt.Printf("%-6s Rs %d\n", name, prices[name])
	}

	// count words
	text := "the cat saw the dog and the dog saw the cat"
	counts := make(map[string]int)
	for _, word := range strings.Fields(text) {
		counts[word]++
	}
	fmt.Println(counts)
}

Output:

0
rice costs 280
flour is not sold here
3
rice   Rs 280
salt   Rs 60
tea    Rs 130
map[and:1 cat:2 dog:2 saw:2 the:4]

The behaviours to remember

Missing keys give the zero value. prices["flour"] returns 0, not an error. That makes counts[word]++ work without setup: a new word starts at zero and becomes one. But it also means you cannot tell "price is zero" from "no such product" by the value alone. Use the comma-ok form, value, ok := m[key], when the difference matters.

Iteration order is random. Go deliberately randomises the order of range over a map, so that nobody depends on it. If you want a stable order, collect and sort the keys first. In Go 1.23 and later, maps.Keys returns an iterator and slices.Sorted turns it into a sorted slice, which is what we did above. Printing a map with fmt.Println is the exception: it sorts keys so the output is readable and repeatable.

Maps are references. If you pass a map to a function, the function sees and changes the same data. No copy is made. Use maps.Clone(m) for a copy.

The nil map trap

A map must be created before you write to it.

var stock map[string]int       // nil map
fmt.Println(stock["tea"])      // 0: reading a nil map is fine
stock["tea"] = 5               // panic: assignment to entry in nil map

Create it with a literal, map[string]int{}, or with make(map[string]int). This is probably the most common map bug, especially for maps stored in struct fields that nobody initialised.

What can be a key

Keys must be comparable with ==: strings, numbers, booleans, arrays, structs made of comparable fields, and pointers. Slices, maps and functions cannot be keys. A struct can be a handy composite key, for example map[Point]string.

Maps are not safe for concurrent use

If several goroutines read and write the same map without protection, Go will often detect it and crash with fatal error: concurrent map writes. Protect the map with a sync.Mutex, or use another design. We handle this in the concurrency lessons.

Strings and strconv

Maps often go together with text processing, so here are the tools you need. The strings package has Split, Fields (splits on any whitespace), Join, Contains, HasPrefix, TrimSpace, ToUpper, Replace and Builder for efficient concatenation. The strconv package converts between text and numbers:

n, err := strconv.Atoi("42")             // string to int
f, err := strconv.ParseFloat("12.50", 64)
s := strconv.Itoa(42)                    // int to string
b, err := strconv.ParseBool("true")

The conversion functions return an error for bad input, such as strconv.Atoi: parsing "abc": invalid syntax. Always check it.

Building a large string with repeated += creates a new string every time. Use strings.Builder:

var sb strings.Builder
for i := range 3 {
	fmt.Fprintf(&sb, "line %d\n", i)
}
fmt.Print(sb.String())

Try it yourself

Write a program with a map from product name to stock count. Add a function sell(stock map[string]int, name string, qty int) error that returns an error when the product does not exist or the stock is too low, and otherwise reduces the stock. Print the stock in alphabetical order after a few sales. Then count how many times each letter appears in a sentence and print the three most common ones.

go
package main

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

func main() {
	prices := map[string]int{
		"tea":   120,
		"sugar": 150,
		"rice":  280,
	}

	prices["salt"] = 60       // add
	prices["tea"] = 130       // update
	delete(prices, "sugar")   // remove (no error if missing)

	// reading a missing key gives the zero value
	fmt.Println(prices["flour"]) // 0

	// the comma-ok idiom tells you whether the key exists
	if price, ok := prices["rice"]; ok {
		fmt.Println("rice costs", price)
	}
	if _, ok := prices["flour"]; !ok {
		fmt.Println("flour is not sold here")
	}

	fmt.Println(len(prices))

	// iterate in sorted key order
	for _, name := range slices.Sorted(maps.Keys(prices)) {
		fmt.Printf("%-6s Rs %d\n", name, prices[name])
	}

	// count words
	text := "the cat saw the dog and the dog saw the cat"
	counts := make(map[string]int)
	for _, word := range strings.Fields(text) {
		counts[word]++
	}
	fmt.Println(counts)
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account