Maps and working with strings
Course contents (17 lessons)
- Getting started with Go
- Installing Go 1.25 and your first program
- Variables, types and constants
- Control flow: if, for and switch
- Functions, multiple returns and defer
- Slices and maps
- Arrays and slices
- Maps and working with strings
- Structs, methods and interfaces
- Structs, methods and pointers
- Interfaces
- Errors, packages and generics
- Error handling the Go way
- Packages and modules
- Generics
- Concurrency
- Goroutines and channels
- select, timeouts and context
- Mutexes, sync and the race detector
- Testing
- Testing and benchmarks
- Building and shipping a service
- Building an HTTP JSON API with net/http
- 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.
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