Go · Stage 10 – Concurrency · Lesson 59 of 64

A Simple Worker

Send jobs to one goroutine and receive results.

Go code

jobs := make(chan int)
results := make(chan int)
go func() {
    job := <-jobs
    results <- job * 2
}()
jobs <- 5
fmt.Println(<-results)
Line-by-line explanation
  1. Two typed channels are created.
  2. The worker waits for one job.
  3. It doubles and sends a result.
  4. Main sends 5.
  5. Main receives and displays 10.
Expected output
10

This is the expected result.