Go · Level 3 Concurrency

Fan-In

Merge two Go channels into one with the fan-in pattern: one goroutine per input, and the output closed only once both inputs are finished.

  • one goroutine per input
  • a WaitGroup counts the inputs
  • close the output once, at the very end

Fan-in merges several channels into one: a goroutine per input copies its values to the output. Trap: close the output only when every input is done; closing it after the first one loses values or panics.

var wg sync.WaitGroup
forward := func(in <-chan string) {
    defer wg.Done()
    for v := range in {
        out <- v
    }
}

Write Merge(a, b <-chan string) <-chan string: one channel with every value from a and b, closed once both are closed. Example: a sends x, y and b sends z → the output carries x, y, z in some order.

solution.go
Test Suites Pending
Output