Golang / GoLang Concurrency Mastery Interview Questions
Implement Go's canonical pipeline pattern with cancellation from the Go blog.
The Go blog defines three-stage pipelines: a generator that produces values, one or more transformation stages, and a consumer — all connected by directional channels, with cancellation via context.
// Stage 1: Generator func generate(ctx context.Context, nums ...int) <-chan int { out := make(chan int) go func() { defer close(out) for _, n := range nums { select { case out <- n: case <-ctx.Done(): return } } }() return out } // Stage 2: Transform func square(ctx context.Context, in <-chan int) <-chan int { out := make(chan int) go func() { defer close(out) for v := range in { select { case out <- v * v: case <-ctx.Done(): return } } }() return out } // Stage 3: Filter func filterAbove(ctx context.Context, in <-chan int, min int) <-chan int { out := make(chan int) go func() { defer close(out) for v := range in { if v <= min { continue } select { case out <- v: case <-ctx.Done(): return } } }() return out } // Consumer func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() nums := generate(ctx, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) squares := square(ctx, nums) results := filterAbove(ctx, squares, 25) for i := 0; i < 3; i++ { fmt.Println(<-results) } cancel() // stops all upstream stages cleanly }
More Related questions...