Go Foundations·Clarity, then concurrency

Goroutines and channels

Concurrency is cheap in Go, but coordination is still your responsibility.

Beginner 15 min read Lesson 9 of 300 Challenge included
What you will be able to do
  • Use context.Context for cancellation and deadlines.
  • Close a channel only from the sender.
  • Run the race detector in tests.

In plain English

A goroutine is a lightweight function running concurrently. Channels pass values between goroutines; sync.WaitGroup waits for a group; context cancels work. Never leave a goroutine blocked forever.

fetch.goGo
func FetchAll(ctx context.Context, urls []string) ([]string, error) {
    results := make(chan string, len(urls))
    var group sync.WaitGroup

    for _, url := range urls {
        group.Add(1)
        go func(url string) {
            defer group.Done()
            body, err := fetch(ctx, url)
            if err == nil {
                results <- body
            }
        }(url)
    }

    group.Wait()
    close(results)

    var bodies []string
    for body := range results {
        bodies = append(bodies, body)
    }
    return bodies, nil
}
Your turn

Wait for workers

Medium

Start two goroutines that print their id, and use a WaitGroup to wait for both.

GO · starter
var group sync.WaitGroup
Check your understanding before moving on.
Knowledge checkQuestion 1

Who should close a channel?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 9 of 300 · 0% of course