How to listen to N channels in Go: dynamic select for an arbitrary number of channels?
Hello everyone! I'm learning Go and ran into a problem. I'm writing a utility that processes events from multiple data sources. Each source runs in its own goroutine and sends data to its own channel. The number of sources is unknown in advance and can change during program execution (the user can add/remove sources).\n\nGo has a `select` construct that allows listening to multiple channels simultaneously. But it's static — you need to specify all `case` statements in advance:\n\n```go\nselect {\ncase msg1 := <-ch1:\n // processing\ncase msg2 := <-ch2:\n // processing\ncase msg3 := <-ch3:\n // processing\n}\n```\n\nBut what if I have a slice of channels `[]chan int` and their number can be 5, 10, or 100? How do I write a dynamic `select` that works with an arbitrary number of channels?
No answers yet.
Log in to leave an answer
Blogs
Top 10 Rust Frameworks for Web Development: Advanced Level
Refactoring Swift Code: When It's Needed and How to Do It Right
Rust: main.rs and lib.rs — how to avoid confusion with modules and speed up code
C++ in 2025: A Complete Learning Plan from Beginner to Pro