Go · Level 3 Concurrency

Channels and close

Build a Go pipeline stage that reads order amounts from a channel, passes on the paid ones and closes its output, so the next stage's range loop can finish.

  • a channel passes values between goroutines
  • range reads until the channel is closed
  • the sender closes, with defer

A channel passes values between goroutines, and for v := range ch reads until the channel is closed. Trap: if the sender never calls close, the reader waits forever and the program deadlocks.

out := make(chan int)
go func() {
    defer close(out)
    for i := 1; i <= 3; i++ {
        out <- i
    }
}()
for n := range out {
    fmt.Println(n)
}

Write Paid(orders <-chan int) <-chan int: a stage that reads order amounts, passes on only the amounts above 0, in the same order, and closes its output when the input ends. Example: 5, 0, 12, -3 in → 5, 12 out.

solution.go
Test Suites Pending
Output