×

go · level 3 · unit 1 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Put go in front of a call and it runs alongside main.

So far your programs did one thing at a time, top to bottom. Write the keyword go in front of a function call and Go starts it as a : a separate strand of work running alongside everything else. Juggling several jobs in overlapping time like this is called .

main is a goroutine too, and when it returns the whole program stops, even if other goroutines are halfway through. So main has to wait. A is a counter for that: Add(1) before starting, Done() when the work is finished, Wait() to pause until the count is zero.

Hand the goroutine a pointer, &wg, so both sides share one counter instead of two separate copies.

package main
import (
	"fmt"
	"sync"
)
func bake(wg *sync.WaitGroup) {
	fmt.Println("Baking the bread...")
	wg.Done()
}
func main() {
	var wg sync.WaitGroup
	wg.Add(1)
	go bake(&wg)
	wg.Wait()
	fmt.Println("Dinner is ready!")
}

Without wg.Wait(), main could finish before the bread is baked, and you might never see that line.