Sobes.tech
Senior

Tell me about the Fan-In pattern, what is it used for?

sobes.tech AI

Answer from AI

The Fan-In pattern in Go is used to merge multiple channels into one. This is useful when you need to gather data from different sources (goroutines) and process it in one place. Essentially, multiple input channels "converge" into a single output channel.

Example implementation of Fan-In:

type Data struct { /* ... */ }

func fanIn(channels ...<-chan Data) <-chan Data {
    out := make(chan Data)
    var wg sync.WaitGroup
    wg.Add(len(channels))

    for _, ch := range channels {
        go func(c <-chan Data) {
            defer wg.Done()
            for v := range c {
                out <- v
            }
        }(ch)
    }

    go func() {
        wg.Wait()
        close(out)
    }()

    return out
}

This approach allows for efficient aggregation of data from multiple sources, simplifying processing and synchronization.