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

Golang for range Loops in 5 Minutes

Go (Golang)5 min video

Go for range loops for beginners, in five minutes, on a real Go program: why changing the value in a range loop leaves the slice unchanged, writing through the index instead, and why a map prints in a different order every run until you sort its keys with slices.Sorted(maps.Keys(m)).

The loop that changed nothing

You wrote a for range loop in Go to change every item in a list. It ran, and the list didn't change. Joe weighs each fish on his charter boat in a bucket that itself weighs 300 grams, so every weight in his catch log is 300 grams too high. He writes a loop that takes 300 off each catch's Grams, its weight.

Joe's laptop: ~/catchlog
sed -n '19,23p' main.go    // take off the 300 g bucket
    for _, c := range catches {
        c.Grams -= 300
        fmt.Println("loop:", c.Fish, c.Grams)
    }

Inside the loop, the mackerel drops to 1200. Then he prints the log, and it still says 1500. The loop did its job. It just did it to something else. So where did the 300 grams go?

Joe's laptop: ~/catchlog
go run .loop: mackerel 1200
loop: sea bass 2100
loop: cod 3800
loop: mackerel 800
loop: pollock 2900
-- log --
mackerel 1500
sea bass 2400
cod 4100
mackerel 1100
pollock 3200

What range hands you

To find them, start with what range really does. Picture the harbour office. The clerk reads the logbook out to you, one line at a time, and you copy each line onto your own notepad. Cross a number out on your notepad, and the logbook doesn't change. That's what range does.

Read out from the logbook, copied onto your notepad: diagram of the logbook, your notepad

Joe's catch log is a slice, Go's word for a list. Each time round, a for range loop over it hands you two things: the position, called the index, and the value at that position. Joe prints both. The first line reads zero, mackerel, 1500, and the last, four, pollock. Go counts positions from zero. His first loop didn't need the index, so he wrote an underscore in its place, which tells Go to throw it away.

Joe's laptop: ~/catchlog
sed -n '19,21p' main.go    for i, c := range catches {
        fmt.Println(i, c.Fish, c.Grams)
    }
Joe's laptop: ~/catchlog
go run .0 mackerel 1500
1 sea bass 2400
2 cod 4100
3 mackerel 1100
4 pollock 3200

Here's where the 300 grams went. That value, c, isn't the catch in the log. Each round, Go puts a fresh copy of the next entry into c. Joe's line changed the copy, like a number crossed out on your notepad. Next round, c is overwritten with the next catch, and the log stays untouched.

Each round, range copies the next entry into c: diagram of catches, c

Change the log, not a copy

To change the log itself, Joe uses the index. Leave out c, and range hands you only the position, which Joe calls i. Then catches.Grams reaches into the log at that position and changes the real entry.

Write through the index: code change of main.go, for i:= range catches { (just the index), catches.Grams -= 300 (into the log)

Now every catch in the log is 300 grams lighter: the mackerel reads 1200, and the pollock 2900.

Joe's laptop: ~/catchlog
go run .-- log --
mackerel 1200
sea bass 2100
cod 3800
mackerel 800
pollock 2900

Range over a number

Joe runs three trips a day. He has no list, just a number. How do you loop exactly three times? Since Go 1.22, range can take a plain number. A number has no items, so range gives just the position: zero, one, two. Joe adds one to print trip 1, 2 and 3.

Joe's laptop: ~/catchlog
sed -n '6,8p' main.go    for trip := range 3 {
        fmt.Println("trip", trip+1, "of 3")
    }
Joe's laptop: ~/catchlog
go run .trip 1 of 3
trip 2 of 3
trip 3 of 3

Ranging over a map

Jess, who sells Joe's catch at the market, wants the total for each kind of fish. Joe adds them up in a map, a lookup from fish name to grams, and ranges over it. On a map, range hands you two things: the fish name, called the key, and its grams, called the value. Then he runs it three times in a row. Guess first: the same order every run? It isn't. Same program, same fish, two different orders.

Joe's laptop: ~/catchlog
sed -n '23,30p' main.go    totals := map[string]int{}
    for _, c := range catches {
        totals[c.Fish] += c.Grams
    }

    for fish, g := range totals {
        fmt.Print(fish, " ", g, "   ")
    }
Joe's laptop: ~/catchlog
for n in 1 2 3; do go run .; donemackerel 2000   sea bass 2100   cod 3800   pollock 2900
mackerel 2000   sea bass 2100   cod 3800   pollock 2900
sea bass 2100   cod 3800   pollock 2900   mackerel 2000

That's on purpose. The Go spec says it plainly: map order isn't specified, and it can change from one loop to the next. Go even starts each loop at a random spot, so no program comes to rely on an order.

Ranging over a map: browser screenshot from the video

When order matters, sort the keys first, with two helpers from Go's standard library. maps.Keys gives Joe the fish names. slices.Sorted puts them in alphabetical order. Then he ranges over that sorted list, looking up each total. Three runs, one order: cod, mackerel, pollock, sea bass.

Joe's laptop: ~/catchlog
sed -n '31,33p' main.go    for _, fish := range slices.Sorted(maps.Keys(totals)) {
        fmt.Print(fish, " ", totals[fish], "   ")
    }
Joe's laptop: ~/catchlog
for n in 1 2 3; do go run .; donecod 3800   mackerel 2000   pollock 2900   sea bass 2100
cod 3800   mackerel 2000   pollock 2900   sea bass 2100
cod 3800   mackerel 2000   pollock 2900   sea bass 2100

Recap

So: range hands you a position and a copy. To change the list, write through the index. Range over a number counts from zero. And a map has no order, so sort the keys when it matters.

Four range habits: cards of Range gives a copy, Write through the index, Range over a number, Sort map keys

If range loops make sense now, a like helps YouTube show this to more beginners, and subscribing brings the next Go idiom: make, for slices and maps.

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 charter boat and its catches 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

Go (Golang)5 min

Golang make() for Slices and Maps in 5 Minutes

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

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