Open-Source Go Programming • Intermediate • Estimated study time: 35 minutes
A map associates unique keys with values. Infrastructure software can use maps to count equipment events, associate identifiers with records or summarize inventory. Unlike a slice, which uses numerical positions, a map retrieves values using keys of a comparable type. Review Go arrays and slices for the distinction.
Prerequisites and learning objectives
Understand variables, zero values, loops and basic Go compilation.
- Create initialized maps and distinguish nil maps from initialized maps.
- Insert, update and delete key-value pairs.
- Use comma-OK lookups to distinguish missing keys from stored zero values.
- Iterate in deterministic order by sorting keys.
- Explain shared map behavior and safe concurrent access.
Creating and updating maps
The type map[string]int associates string keys with integer values. A literal such as map[string]int{“R01”: 0} creates an initialized map with one entry. The expression make(map[string]int) creates an empty initialized map. A declaration var m map[string]int creates a nil map: reads return the element type’s zero value, but assignment to an entry panics. The Go language specification defines which key types are permitted. Comparable values such as strings and integers can be keys; slices cannot.
Assign counts[“R02”] = 1 to insert or replace a value. The expression counts[“R02”]++ increments its current count. The built-in delete(counts, “R02”) removes the entry; deleting a missing key is harmless. len(counts) returns the number of entries.
Missing versus zero
Reading an absent integer key returns zero, which is also a valid stored value. Use n, ok := counts[“R03”] to obtain both the value and a boolean indicating presence. If ok is false, the key is absent. The earlier variables and zero values lesson explains default values. The official Tour of Go demonstrates mutation and presence checks.
Practice: inventory event counts
The following fictional inventory example counts three events, preserves a deliberately stored zero and removes one key. The iteration order of a Go map is unspecified. Collect its keys into a slice and sort them before producing a deterministic report. Review for and range control flow for the loops.
package main
import (
“fmt”
“sort”
)
func main() {
counts := map[string]int{“R01”: 0}
for _, rack := range []string{“R02”, “R01”, “R02”} {
counts[rack]++
}
counts[“R03”] = 0
delete(counts, “R01”)
if _, ok := counts[“R01”]; ok { panic(“delete failed”) }
if n, ok := counts[“R03”]; !ok || n != 0 { panic(“zero lookup failed”) }
keys := make([]string, 0, len(counts))
for k := range counts { keys = append(keys, k) }
sort.Strings(keys)
for _, k := range keys { fmt.Printf(“%s: %d\n”, k, counts[k]) }
}
Build and interpret
Save the program as maps.go. Following the Go toolchain lesson, run go run maps.go. Expected output, in order:
R02: 2
R03: 0
The two explicit checks terminate the program if deletion or zero-value lookup behaves incorrectly. The example is sequential and uses fictional data. Assigning one map variable to another does not independently copy its entries: changes through either variable affect the shared map. Ordinary maps need synchronization when shared across goroutines with writes. Use a mutex or another suitable ownership strategy. Consult Go maps in action. Do not use production inventory records in unsupervised practice.
Exercises and answer key
- What does an absent integer key return? Answer: zero; use comma-OK to determine presence.
- Can a nil map accept a new entry? Answer: no; initialize it first.
- Does range guarantee sorted map keys? Answer: no; extract and sort keys.
- How many entries remain after removing R01 in the example? Answer: two.
- Does assigning a map to another variable create an independent copy? Answer: no.
Featured photograph: Go gopher, SimonWaldherr, Wikimedia Commons, CC BY-SA 4.0; cropped.
We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiative, please scan the QR code below.

BitcoinVersus.tech is not a financial advisor. This media platform reports on financial subjects purely for informational purposes.

Leave a Reply