Maps in Go

Contents
Make and fill
Read with comma-ok
Delete keys
Iterate in random order

Make and fill

A map stores key and value pairs with fast lookup by key. Declare one with a literal when the content is known, or with make and fill it step by step when keys arrive later.

package main import "fmt" func main() { ages := map[string]int{"Ada": 36, "Bob": 28} fmt.Println(ages) scores := make(map[string]int) scores["Cid"] = 10 fmt.Println(scores) }

go run main.go

map[Ada:36 Bob:28]
map[Cid:10]

A map declared with plain var and no make is nil: reading it is safe, but writing to it panics. When in doubt, create every map with a literal or with make.

Read with comma-ok

Reading a missing key returns the zero value instead of failing, which makes typos silent. The comma ok form reports whether the key was really there, so always use it when absence matters.

package main import "fmt" func main() { ages := map[string]int{"Ada": 36} age, ok := ages["Ada"] fmt.Println(age, ok) zero, found := ages["Zed"] fmt.Println(zero, found) }

36 true
0 false

The second value is true only when the key exists. Branch on it to tell a stored zero apart from a missing entry.

Delete keys

Delete removes a key and its value in one call, and deleting a key that is absent is simply a quiet no op. Maps need no cleanup beyond that: unused entries vanish with the map itself.

package main import "fmt" func main() { ages := map[string]int{"Ada": 36, "Bob": 28} delete(ages, "Bob") fmt.Println(ages) }

map[Ada:36]

There is no error to check here: delete always succeeds. To clear everything at once, simply make a fresh map and let the old one go.

Iterate in random order

Range over a map visits every pair exactly once, but in a fresh random order on each run. That randomness keeps programs honest: any logic that needs order must sort explicitly.

package main import "fmt" func main() { ages := map[string]int{"Ada": 36, "Bob": 28, "Cid": 41} for name, age := range ages { fmt.Println(name, age) } }

Run this program twice and the lines may swap places. For stable output, collect the keys into a slice, sort the slice, and then read the map in that order.

Next: Functions

Article author: Arthur Isaev

Related articles
Golang
Go course: zero to hero in 50 lessons
What is Go and where it runs
Install Go and check the version
Your first Go program
Modules with go mod
Variables
Constants
Types
Numbers
Strings
Conditions with if
Switch in Go
Loops with for
Arrays in Go
Slices in Go
Maps in Go
Functions in Go
Errors as values
Pointers in Go
Structs in Go
Methods in Go
Interfaces in Go
Embedding instead of inheritance
Generics in Go
Packages and imports
The go toolchain
Testing with go test
Advanced errors
defer in Go
Strings, bytes and runes
Time in Go
JSON
Files and IO
HTTP servers
HTTP clients
Context
Goroutines
Channels
select and sync
CLI: args, flags, env
Logging
Regular expressions
Sorting
Concurrency patterns
Databases with database/sql
Benchmarks and profiling
Toolchain and CI
Project layout
Capstone: wordfreq CLI
Capstone: JSON API server
Hero roadmap: the whole course on one page
Install Go on Windows 11
Install Go on Ubuntu
Install Go on Rocky Linux
Install Go on macOS
Install Go on FreeBSD
Go in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: