AnyCompiler

Goroutines

A goroutine is a lightweight, independently-running function, started by putting go in front of a function call. Goroutines are cheap — a Go program can run thousands of them at once — and they're a core part of the language itself, not an add-on library.

package main

import (
	"fmt"
	"sync"
)

func main() {
	var wg sync.WaitGroup
	results := make([]int, 3)

	for i := 0; i < 3; i++ {
		wg.Add(1)
		go func(index int) {
			defer wg.Done()
			results[index] = index * index
		}(i)
	}

	wg.Wait()
	fmt.Println(results)
}
Output
[0 1 4]

sync.WaitGroup is how main waits for a group of goroutines to finish before continuing — wg.Add(1) registers one goroutine to wait for, and each goroutine calls wg.Done() when it completes; wg.Wait() blocks until every registered goroutine has checked in.

Next: channels — how goroutines communicate with each other safely.

Practice exercise

Use a sync.WaitGroup to run a goroutine that sets a variable result := 0 to 100, waiting for it to finish before printing result.