Cloud Explainers
Home › Go (Golang) › Golang Idioms for Beginners, episode 8

Golang make() for Slices and Maps in 5 Minutes

Go (Golang)5 min video

Go's make() for beginners, in five minutes, on a real Go program: why writing to a map that was only declared panics with 'assignment to entry in nil map', how make builds a real map, what make's length and capacity mean for slices, the make-then-append bug that leaves zeros in front, and how much a capacity up front saves when appending thousands of items.

Reading works, writing panics

Your Go program just crashed, and the error says: assignment to entry in nil map. Trish runs an apple orchard. She uses a Go map to count the bins of each apple variety. She asks it how many Gala bins so far, and it answers zero. Then she adds fourteen, and the program crashes. Asking was fine. Adding was not. The fix is one built-in function, make. And for slices, Go's lists, make also decides whether your program wastes time copying the whole list, again and again.

Trish's laptop: ~/harvest
sed -n '6,10p' main.go    var bins map[string]int

    fmt.Println("Gala bins so far:", bins["Gala"])
    bins["Gala"] += 14
    fmt.Println("Gala bins:", bins["Gala"])
Trish's laptop: ~/harvest
go run .Gala bins so far: 0
panic: assignment to entry in nil map

goroutine 1 [running]:
main.main()
    /home/trish/harvest/main.go:9 +0xa4
exit status 2

Here's why. Look at the line that declares bins. It gives Trish a name, but no map behind it. Its value is nil, Go's word for nothing there yet. Reading a key from a nil map is allowed. You just get the starting value for an int, which is zero. But adding an entry needs somewhere to put it, and there's nowhere.

A name, but no map behind it: diagram of var bins map int, var bins = A name, map int = Its type, Value: nil. Reads give 0, writes have nowhere to go

The Go spec, the official rulebook for the language, says it in one line: a nil map is like an empty map, except that no elements may be added. And the line above it names the fix: a new, empty map is made with the built-in function make.

Reading works, writing panics: browser screenshot from the video

make for maps

So Trish changes one line. Instead of declaring an empty name, she asks make for a map: make, then the map's type, map of string to int. The colon-equals sign declares bins and gives it the new map in one step.

Ask make for a real map: code change of main.go, bins:= make(map int) (a real, empty map)

Now she adds three loads: fourteen Gala, nine Fuji, then eleven more Gala. The map holds two varieties: Fuji nine, Gala twenty-five. One make, and every write just works.

Trish's laptop: ~/harvest
sed -n '6,12p' main.go    bins := make(map[string]int)

    fmt.Println("Gala bins so far:", bins["Gala"])
    bins["Gala"] += 14
    bins["Fuji"] += 9
    bins["Gala"] += 11
    fmt.Println("bins:", bins, "varieties:", len(bins))
Trish's laptop: ~/harvest
go run .Gala bins so far: 0
bins: map[Fuji:9 Gala:25] varieties: 2

make for slices: length

Now a trap. Make builds slices too, Go's lists, and this one catches people all the time. Trish wants the bins picked in each of her three rows. She knows there are three, so she calls make with the type, a slice of ints, and the number three. Then she appends each row's count: fourteen, nine, eleven. Append adds a value to the end and hands back the longer slice, so she stores it back. Guess first: how many numbers print? Six. Three zeros, then her three counts.

Trish's laptop: ~/harvest
sed -n '8,12p' main.go    perRow := make([]int, 3)
    for _, n := range picked {
        perRow = append(perRow, n)
    }
    fmt.Println(perRow, "len", len(perRow))
Trish's laptop: ~/harvest
go run .[0 0 0 14 9 11] len 6

Picture the end of an orchard row. Calling make with the number three sets out three crates, and counts them as already filled, each one holding a zero. That count is the length. Append never fills those crates. It always puts the next load after the last counted one, in crate four.

Length: the crates counted as filled: diagram of crate 1, crate 2, crate 3, crate 4, length 3

The fix is a second number: make with zero, then three. Zero is the length, so none are counted yet. Three is the capacity: three empty crates set out and waiting. Now append fills crate one first, and the slice holds just fourteen, nine and eleven.

Trish's laptop: ~/harvest
sed -n '8,8p' main.go    perRow := make([]int, 0, 3)
Trish's laptop: ~/harvest
go run .[14 9 11] len 3 cap 3

The spec's table says the same. With one number, the length and the capacity are both that number. With two, the first is the length, the second the capacity.

make for slices: length: browser screenshot from the video

Capacity: room to grow

So why set out crates at all? Trish starts a slice with no make, just declared. Unlike a nil map, a nil slice is fine to append to. Append sets out the crates for you. Go calls that row of crates an array, and the slice sits on top of it. She appends twenty bins, one at a time, and prints a line each time the capacity changes. The capacity went from zero to four, then eight, sixteen and thirty-two, doubled each time it filled up.

Trish's laptop: ~/harvest
sed -n '6,15p' main.go    var crates []int // nil: no array behind it yet
    fmt.Println("nil?", crates == nil, "len", len(crates), "cap", cap(crates))

    for bin := 1; bin <= 20; bin++ {
        before := cap(crates)
        crates = append(crates, bin)
        if cap(crates) != before {
            fmt.Println("len", len(crates), "cap", cap(crates), "<- new, bigger array")
        }
    }
Trish's laptop: ~/harvest
go run .nil? true len 0 cap 0
len 1 cap 4 <- new, bigger array
len 5 cap 8 <- new, bigger array
len 9 cap 16 <- new, bigger array
len 17 cap 32 <- new, bigger array

Each of those lines is a move. When every crate in the array is full, append can't squeeze in one more. It gets a new, bigger array, copies every bin across, and the slice points to the new one. For a few bins that's nothing. For thousands, it adds up.

When the crates run out, append moves everything: diagram of crates, old array, new array

Trish measures it with Go's benchmark tool. It adds ten thousand bins two ways: once growing from nothing, and once with make and the full capacity up front. It runs each version thousands of times, and counts every time it asks for new memory. Growing from nothing asked for new memory 18 times. Each time meant a new array and a full copy. That took about 19 microseconds. With make, it asked once, in about 4 microseconds. Four times faster on her laptop.

Trish's laptop: ~/harvest
sed -n '10,16p' main.gofunc grow(n int) []int {
    var s []int
    for i := range n {
        s = append(s, i)
    }
    return s
}
Trish's laptop: ~/harvest
go test -bench . -benchmem -cpu 1goos: linux
goarch: arm64
pkg: harvest
BenchmarkGrow          83251         19006 ns/op      357624 B/op         18 allocs/op
BenchmarkPresized     283748          4227 ns/op       81920 B/op          1 allocs/op
PASS
ok      harvest 2.783s

Recap

So: a declared map is nil, fine to read, a panic to write. Make it first. For slices, make's first number is the length, the second the capacity. Never give it a length and then append on top. And when you know the count, give it the capacity.

Four make habits: cards of Make the map first, Length, then capacity, Not length, then append, Know the count?

If make makes sense now, a like helps YouTube show this to more beginners, and subscribing brings the next Go idiom: defer.

All the lab files and commands are linked in the description. Thanks for watching Cloud Explainers.

Sources

Demos: one container on our own Mac standing in for a laptop; the orchard and its harvest are made up. Every command, output and number was real. Watch the full video on YouTube.

More videos

PostgreSQL9 min

Every PostgreSQL Setting to Change After You Install It

Docker9 min

What Happens When You Install Docker on Ubuntu

Python8 min

How to Fix Python 'Address Already in Use' Errors

Go (Golang)5 min

Golang Interfaces and Mocks in 5 Minutes

Git7 min

How to Fix Git 'Detached HEAD' State

Linux21 min

Linux Firewall with ufw: Full Tutorial for Beginners

Go (Golang)5 min

Golang defer Statements in 5 Minutes

Auth (OAuth, JWT)9 min

How to Fix OAuth 'invalid_grant' Errors

Databases & SQL11 min

The SQL Roadmap for Beginners

Networking7 min

How to Fix Network 'No Route to Host' Errors on Linux

Linux6 min

How to Fix Linux 'Too Many Open Files' Errors

Django (Python web framework)11 min

Every Django Concept a Beginner Needs to Know

Linux24 min

SSH on Linux: Full Tutorial for Beginners

Go (Golang)5 min

Golang for range Loops in 5 Minutes

Databases & SQL10 min

SQL Databases: SQLite vs PostgreSQL

Django (Python web framework)10 min

The Django Roadmap for Beginners

Go (Golang)5 min

Golang Structs in 5 Minutes

Caching & Redis22 min

Redis: Full Tutorial for Beginners

Go (Golang)5 min

Golang context.Context in 5 Minutes

Databases & SQL7 min

How to Fix MySQL Database Error 1045: Access Denied for User

Go (Golang)5 min

Golang Method Receivers in 5 Minutes

Python8 min

How to Fix Python SSL: CERTIFICATE_VERIFY_FAILED Errors

Django (Python web framework)9 min

How to Fix Django Static Files Not Loading in Production

OpenRouter (one API for many AI models)8 min

OpenRouter vs Direct API Keys: Which One Should You Use?

Go (Golang)5 min

Golang if err != nil Checks in 5 Minutes

Go (Golang)8 min

How to Fix Golang 'go.mod File Not Found' Errors

AI agents & MCP22 min

MCP Servers: Full Tutorial for Beginners

Go (Golang)5 min

Golang Error Return Values in 5 Minutes

Python8 min

How to Fix Python ModuleNotFoundError: No Module Named

Go (Golang)5 min

Golang Pointers in 5 Minutes

Kubernetes8 min

How to Fix a Kubernetes Pod Stuck in CrashLoopBackOff

Homelab & self-hosting9 min

How to Fix a Homelab ESXi Host Not Responding

PostgreSQL24 min

PostgreSQL: Full Tutorial for Beginners

Load balancing & Nginx9 min

How a Load Balancer Works with HAProxy

Python9 min

How Python Virtual Environments Work

Homelab & self-hosting9 min

How to Fix Cloudflare Tunnel Errors in a Homelab

APIs9 min

How to Fix API CORS Errors: No 'Access-Control-Allow-Origin'

Auth (OAuth, JWT)9 min

How Authenticator App Login Codes Work (TOTP)

Git22 min

Git and GitHub: Full Tutorial for Beginners

Homelab & self-hosting10 min

How a Homelab Hypervisor Works (VMware ESXi)

Kubernetes9 min

How to Fix Kubernetes ImagePullBackOff Errors

DNS8 min

How to Fix DNS 'Temporary Failure in Name Resolution' on Linux

AWS8 min

How to Fix AWS CLI 'Unable to Locate Credentials'

Homelab & self-hosting10 min

Proxmox vs ESXi for Your Homelab: When Each One Wins

PostgreSQL10 min

PostgreSQL UUID vs Auto Increment: Which Primary Key Should You Use?

Kubernetes21 min

Kubernetes: Full Tutorial for Beginners

Networking9 min

How TCP Sockets Work

PostgreSQL7 min

How to Fix PostgreSQL 'Could Not Connect to Server'

Claude & the Claude Developer Platform9 min

Claude Code Hooks Will Finally Make Sense After This

DevOps & CI/CD9 min

DevOps with Ansible Will Finally Make Sense After This

Networking9 min

How SNMP Network Monitoring Works

Git8 min

How to Fix GitHub 'Permission Denied (publickey)' Errors

Docker21 min

Docker: Full Tutorial for Beginners

PostgreSQL7 min

How to Fix PostgreSQL 'Password Authentication Failed'

Linux8 min

Why One Linux Server Handles More Users Than You Think

Networking7 min

How to Fix Network 'Connection Refused' Errors

DevOps & CI/CD9 min

DevOps Pipelines: Jenkins vs GitHub Actions

Linux11 min

Linux Nginx Reverse Proxy: Full Tutorial for Beginners

Networking11 min

Every Networking Term a Beginner Needs in 12 Minutes

Docker6 min

How to Fix Docker 'Permission Denied' on docker.sock

Git7 min

How to Fix Git 'Updates Were Rejected' When You Push

Linux7 min

How to Fix nginx 502 Bad Gateway Errors on Linux

Linux8 min

How to Fix Linux apt 'Could Not Get Lock' Errors (Ubuntu)

Networking9 min

How Email Works on the Internet (SMTP) in 10 Minutes

Python8 min

The Python Roadmap for Beginners

Go (Golang)21 min

Golang REST API with Gin: Full Tutorial for Beginners

Networking10 min

How a WireGuard VPN Network Works

Linux9 min

Linux Makefiles Will Finally Make Sense After This

Auth (OAuth, JWT)9 min

SAML vs OAuth vs OpenID Connect: What's the Difference?

Python7 min

How to Fix Python cron Jobs That Never Run

Linux22 min

Linux Bash Scripting: Full Tutorial for Beginners

Networking10 min

How PXE Network Boot Works

Active Directory9 min

How Active Directory Works

Linux10 min

How to Fix a Linux systemd Service That Won't Start

Linux9 min

Linux Logs: syslog vs journald

Auth (OAuth, JWT)9 min

JWT vs Session Cookies: Which One Should You Use?

Docker10 min

Docker vs Docker Compose: Which One Should You Use?

Docker9 min

How to Fix Docker Compose Containers That Can't Talk to Each Other

Django (Python web framework)22 min

Django Full Tutorial for Beginners

Linux9 min

How Linux systemd Works

Networking8 min

How to Fix 'Windows Cannot Access' Network Share Errors (SMB)

APIs10 min

REST vs gRPC: Which One Should You Use?

Certificates & PKI (ADCS)9 min

How to Fix SSL Certificate Chain Errors (Missing Intermediate)

Python9 min

Every Python Concept for Beginners in 10 Minutes

Databases & SQL9 min

Every SQL Join Type in 10 Minutes

OpenRouter (one API for many AI models)9 min

Why OpenRouter Free Models Hit Their Limit So Fast

Gemini API & Google AI Studio9 min

Why Your Gemini API Free Tier Runs Out So Fast

OpenRouter (one API for many AI models)10 min

OpenRouter Will Finally Make Sense After This

Caching & Redis10 min

How Redis Caching Works

Gemini API & Google AI Studio10 min

Gemini API vs Vertex AI: Which One Should You Use?

Gemini API & Google AI Studio8 min

How to Fix a Leaked Gemini API Key

Go (Golang)9 min

Why Golang Uses Goroutines Instead of Threads

Gemini API & Google AI Studio9 min

How to Fix Gemini API Error 429: Resource Exhausted

Claude & the Claude Developer Platform10 min

Claude Token Pricing Will Finally Make Sense After This

Python11 min

Why Python Web Scraping Returns Nothing (and the Fix)

Python10 min

Python uv vs pip: Which One Should You Use?

Python22 min

Python Automation: Full Tutorial for Beginners

Auth (OAuth, JWT)9 min

How OAuth Login Works

Gemini API & Google AI Studio10 min

Google AI Studio Will Finally Make Sense After This

Docker10 min

What Happens When You Run a Docker Container

Claude & the Claude Developer Platform8 min

How to Fix Claude Code Billing Your API Key Instead of Your Plan

Auth (OAuth, JWT)9 min

Why Passkeys Can't Be Phished Like Passwords

PowerShell10 min

PowerShell vs Bash: Which One Should You Learn?

Linux10 min

The Linux Roadmap for Beginners

Django (Python web framework)9 min

Django vs FastAPI: Which One Should You Use?

Databases & SQL10 min

Why SQLite Is the Most Used Database in the World

Databases & SQL11 min

How a NoSQL Database Like MongoDB Works

Python11 min

How to Fix Python pip error: externally-managed-environment

Databases & SQL9 min

How to Fix MySQL Too Many Connections Database Errors

Go (Golang)9 min

Golang Concurrency Will Finally Make Sense After This

AWS10 min

How Amazon S3 Works

Kubernetes10 min

How Kubernetes Works

Git10 min

How Git Works

Docker10 min

How to Fix Docker Port Already Allocated Errors

PostgreSQL10 min

How PostgreSQL Works

Git8 min

How to Fix Git Merge Conflicts

Linux9 min

How to Fix No Space Left on Device in Linux

Networking10 min

How the Internet Works

Databases & SQL9 min

SQL vs NoSQL: When Each One Wins

Auth (OAuth, JWT)8 min

How to Fix JWT Token Expired Errors (401 Unauthorized)

Claude & the Claude Developer Platform9 min

Claude API vs Claude Pro: Why Your Subscription Doesn't Include It

AI agent skills9 min

Why AI Agent Skills Beat Giant Prompts

Linux10 min

Linux Cron Jobs Will Finally Make Sense After This

Cybersecurity10 min

Security Logs Will Finally Make Sense After This

Cybersecurity8 min

How to Fix a Security Leak: An API Key Pushed to GitHub

DNS9 min

DNS Will Finally Make Sense After This

Cybersecurity9 min

Never Ignore a Security Update

Auth (OAuth, JWT)9 min

Two-Factor Authentication Will Finally Make Sense

Networking8 min

Never Expose a Database to the Internet

Cybersecurity10 min

SSH Keys vs Passwords: Which Is Safer for Security?

Linux10 min

The 5 Levels of Linux Boot: From Power On to Login

Networking12 min

The 5 Levels of Network Firewalls

Cybersecurity10 min

Password Security: Why Hackers Crack Weak Passwords

Linux9 min

Why Your Linux Server Runs Out of Memory

Networking10 min

HTTP vs HTTPS: What Actually Changes on Your Network

Linux12 min

Every Linux File Permission You Need to Know

Linux10 min

Linux Processes vs Threads: When Each One Wins

Networking11 min

The OSI Model Will Finally Make Sense After This

Git11 min

The 7 Levels of Git

Networking10 min

Every Network Troubleshooting Command You Need

Cybersecurity10 min

Hashing vs Encryption in Cybersecurity: When Each One Wins

Networking11 min

Why the Internet Ran Out of IP Addresses

Linux11 min

Linux Package Managers: apt vs Snap vs Flatpak

Python9 min

Why Python Is Slow (and When It Doesn't Matter)

Networking11 min

TCP vs UDP: When Each One Wins

Linux8 min

Stop Running Linux as Root (Do This Instead)

Linux11 min

Linux Users and Groups Will Finally Make Sense

Cybersecurity9 min

Why Phishing Beats Good Security (and How to Spot It)

Docker12 min

The 7 Levels of Docker

AI agents & MCP12 min

AI Agents Will Finally Make Sense After This

Git8 min

Stop Using git push --force (Use This Instead)

AI agent skills10 min

Agent Skills vs MCP: When Each One Wins

Networking12 min

Networking Will Finally Make Sense After This

Linux12 min

Every Linux Command You Actually Need

Cybersecurity12 min

The 7 Levels of Cybersecurity

System design12 min

Every System Design Concept You Need, in One Diagram

PostgreSQL10 min

Why PostgreSQL Ignores Your Index