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

Golang go func(): Starting Goroutines in 5 Minutes

Go (Golang)5 min video

Go's go statement for beginners, in five minutes, on a real Go program: why putting go in front of three slow calls makes the program finish in zero seconds with none of them run, what the go statement does, why main never waits for goroutines, how sync.WaitGroup (Add, Done, Wait) fixes it, what go func() { ... }() means and why the final () matters, how 100,000 goroutines finish in about a second, and how go run -race and a sync.Mutex catch and fix a data race.

Golang go func(): Starting Goroutines in 5 Minutes, the full picture: diagram of wg.Add(3), emailReceipt, updateStock, printLabel, wg.Wait(), main returns, three goroutines
The whole picture, from the video's recap.

Faster, and nothing ran

Put the keyword go in front of three slow calls, and your checkout drops from three seconds to zero. But nothing ran. Here's why, and how go func fixes it.

go in front of three slow calls: comparison table of With go in front vs By the end of this video, go run., Receipt emailed, Stock updated, Label printed, The fix

Here's the checkout. After every order, it emails a receipt, updates the stock, and prints a label, one after another.

your laptop: ~/checkout
go run .receipt emailed
stock updated
label printed
done in 3.01s

What go really does

So what does go actually do? Write it before a function call, and Go starts a goroutine: the function runs on its own, while your next line runs right away.

The go statement: start it, and move on: diagram of go emailReceipt(order), go = the go statement, emailReceipt = any function call, (order) = its arguments, It runs on its own: your next line doesn't wait

So put go in front of all three, and run it. It finishes in zero seconds, and not one line of output from the three jobs. All three goroutines did start. But every Go program starts in a function called main, and main reached its last line first.

your laptop: ~/checkout
sed -n '28,30p' main.go    go emailReceipt(order)
    go updateStock(order)
    go printLabel(order)
your laptop: ~/checkout
go run .done in 0.00s

And Go's specification says what happens next: the program exits. It does not wait for other goroutines.

Picture a shop at closing time. You send three helpers out on errands, then lock the door straight away. The fix is a sign-out sheet: you lock up only when everyone has signed back in.

Make main wait

In Go, that sheet is called a WaitGroup. It lives in Go's sync package, and here we name it wg. Before starting the jobs, main calls Add with three. That means: expect three jobs. Each goroutine signs back in when it finishes, by calling Done. And main stops at Wait, until the count is back to zero. Only then does main return. But who calls Done? emailReceipt doesn't know about our WaitGroup.

So wrap each call in a small function with no name, and let that function call Done. On screen: the word go, then func, Go's word for a function, and two empty parentheses at the very end. That's go func.

go func(): wrap each call: code change of main.go, go func() { defer wg.Done(); emailReceipt(order) }() (wrap the call), go func() { defer wg.Done(); updateStock(order) }() (the wrapper calls wg.Done())

The first line inside says defer wg dot Done. Defer means: run this when the function finishes, however it finishes. Then comes the real call. And those last parentheses call the function right now.

your laptop: ~/checkout
sed -n '29,34p' main.go    var wg sync.WaitGroup
    wg.Add(3)
    go func() { defer wg.Done(); emailReceipt(order) }()
    go func() { defer wg.Done(); updateStock(order) }()
    go func() { defer wg.Done(); printLabel(order) }()
    wg.Wait()

Watch what happens if you delete them on one line. The build stops. The compiler says: expression in go must be function call. You wrote a function, and never called it. Now put them back and run it again: all three jobs, in whatever order they finish, done in one second, not three.

your laptop: ~/checkout
go run .# checkout
./main.go:31:5: expression in go must be function call
your laptop: ~/checkout
go run .stock updated
label printed
receipt emailed
done in 1.01s

On Go one twenty-five or newer, the WaitGroup has a shortcut method, also called Go: give it your function, with no extra parentheses, and it calls Add, starts the goroutine, and calls Done for you.

The same wait, two ways to write it: comparison table of go func() {... }() vs wg.Go(func() {... }), Works in, Then wait, Final (), Add and Done, go run.

Thousands at once

A real checkout doesn't get three orders, it gets thousands at once. Let's email a hundred thousand receipts, a goroutine each, every one waiting a full second. Guess first: how long does that take? About one second. They all wait at the same time. And a new goroutine starts with only a few kilobytes of memory, so a laptop holds a hundred thousand easily.

your laptop: ~/checkout
sed -n '17,22p' main.go    var wg sync.WaitGroup
    for order := range 100000 {
        wg.Add(1)
        go func() { defer wg.Done(); emailReceipt(order) }()
    }
    wg.Wait()
your laptop: ~/checkout
go run .receipts emailed: 100000
done in 1.08s

One trap is left. Start a thousand goroutines, and have each one add one to a shared counter of receipts sent. Guess first: what's the final count? It should be one thousand. We got seven hundred sixty-seven. Run it again: eight hundred sixty-four. Two goroutines both read forty-one, both add one, and both write forty-two. Two receipts were sent, but the count only went up by one. That's a data race.

your laptop: ~/checkout
sed -n '9,18p' main.go    sent := 0

    var wg sync.WaitGroup
    for range 1000 {
        wg.Add(1)
        go func() { defer wg.Done(); sent++ }()
    }
    wg.Wait()

    fmt.Println("receipts sent:", sent)
your laptop: ~/checkout
go run .receipts sent: 767
your laptop: ~/checkout
go run .receipts sent: 864

Go can catch this for you. Run with dash race, and it prints: warning, data race, with the line number. The fix is a mutex, a lock, from the same sync package. Call Lock before touching the counter, and Unlock right after, so only one goroutine is in there at a time. Now it's one thousand, and the race detector stays quiet.

your laptop: ~/checkout
go run -race .==================
WARNING: DATA RACE
Read at 0x00c000014108 by goroutine 16:
  main.main.func1()
      /home/dev/checkout/main.go:14 +0x68

Previous write at 0x00c000014108 by goroutine 26:
  main.main.func1()
      /home/dev/checkout/main.go:14 +0x78

Goroutine 16 (running) created at:
  main.main()
      /home/dev/checkout/main.go:14 +0x6c

Goroutine 26 (finished) created at:
  main.main()
      /home/dev/checkout/main.go:14 +0x6c
==================
==================
WARNING: DATA RACE
Write at 0x00c000014108 by goroutine 16:
  main.main.func1()
      /home/dev/checkout/main.go:14 +0x78

Previous write at 0x00c000014108 by goroutine 23:
  main.main.func1()
      /home/dev/checkout/main.go:14 +0x78

Goroutine 16 (running) created at:
  main.main()
      /home/dev/checkout/main.go:14 +0x6c

Goroutine 23 (finished) created at:
  main.main()
      /home/dev/checkout/main.go:14 +0x6c
==================
receipts sent: 655
Found 2 data race(s)
exit status 66
your laptop: ~/checkout
sed -n '9,19p' main.go    sent := 0
    var mu sync.Mutex

    var wg sync.WaitGroup
    for range 1000 {
        wg.Add(1)
        go func() { defer wg.Done(); mu.Lock(); sent++; mu.Unlock() }()
    }
    wg.Wait()

    fmt.Println("receipts sent:", sent)
your laptop: ~/checkout
go run -race .receipts sent: 1000

Recap

So: go starts a function, and never waits. When main returns, everything stops. A WaitGroup makes main wait. Go func wraps a call, so it can call Done. And shared data needs a lock. Run with dash race to find where.

Starting goroutines, in short: cards of go f(x), main returns, sync.WaitGroup, go func() {... }(), sync.Mutex, go run -race

If your goroutines finally finish, subscribing keeps more Go idioms coming: one idea, one real program, five minutes at a time.

The lab and every command are linked in the description, so you can run every step on your own laptop. Thanks for watching Cloud Explainers.

Sources

Demos: one container on our own Mac standing in for your laptop; the checkout and its jobs are made up (each job just waits one second). Every command, output and number was real. Watch the full video on YouTube.

More videos

Kubernetes10 min

Docker vs Kubernetes: What's the Difference?

HTTP & HTTPS11 min

Every HTTP Status Code You Need to Know

PostgreSQL8 min

How to Fix PostgreSQL 'Relation Does Not Exist' Errors

Git9 min

Git Merge vs Rebase: Which One Should You Use?

APIs10 min

How API Webhooks Work

LLM infrastructure9 min

How LLM Tokens Work

Docker9 min

Docker Containers vs Virtual Machines: What's the Difference?

PostgreSQL9 min

MySQL vs PostgreSQL: Which One Should You Use?

Local LLMs (Ollama)15 min

Ollama: Full Tutorial for Beginners

GitHub Actions15 min

GitHub Actions: Full Tutorial for Beginners

Certificates & PKI (ADCS)8 min

How to Fix Certificate Errors: 'Your Connection Is Not Private'

AWS9 min

How the Amazon Ergo AI Model Works

LLM infrastructure9 min

How to Fix LLM API Rate Limit Errors (429)

LLM infrastructure9 min

RAG vs Fine-Tuning: Which One Should You Use?

Load balancing & Nginx24 min

Nginx: Full Tutorial for Beginners

Terraform23 min

Terraform: Full Tutorial for Beginners

Go (Golang)5 min

Golang Generics ([T any]) in 5 Minutes

AWS9 min

How AWS Bedrock Works

LLM infrastructure8 min

How LLM Embeddings Work

Python9 min

How to Fix Python CUDA Memory Errors in PyTorch

Go (Golang)5 min

Golang Type Assertions in 5 Minutes

LLM infrastructure10 min

CPU vs GPU for LLM Inference: What Actually Changes

Google Colab (Jupyter notebooks in the cloud)15 min

Google Colab: Full Tutorial for Beginners

AWS8 min

Amazon Bedrock vs OpenRouter: Which One Should You Use?

Go (Golang)5 min

Golang Channels (chan) in 5 Minutes

Homelab & self-hosting21 min

Tailscale: Full Tutorial for Beginners

LLM infrastructure9 min

How RAG Works

Git11 min

Every Git Setting to Change on Day One

Linux9 min

WSL vs a Linux Virtual Machine: Which One Should You Use?

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

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