Golang / GoLang Concurrency Mastery Interview Questions
How does the select statement work in Go and what are its key properties?
select is Go's multiplexed channel operation. It waits on multiple channel operations simultaneously and proceeds with the first one that is ready. It is the primary tool for non-blocking operations, timeouts, and cancellation in concurrent code.
// Basic select — whichever channel has data first
ch1 := make(chan string, 1)
ch2 := make(chan string, 1)
ch1 <- "one"
ch2 <- "two"
select {
case msg := <-ch1:
fmt.Println("ch1:", msg)
case msg := <-ch2:
fmt.Println("ch2:", msg)
}
// If MULTIPLE cases are ready: Go picks ONE AT RANDOM
// Non-blocking operation with default
ch := make(chan int, 1)
select {
case v := <-ch:
fmt.Println("received:", v)
default:
fmt.Println("no value ready — returns immediately")
}
// Timeout pattern
func fetchWithTimeout(url string, d time.Duration) ([]byte, error) {
result := make(chan []byte, 1) // buffered — prevents goroutine leak!
go func() {
resp, _ := http.Get(url)
body, _ := io.ReadAll(resp.Body)
result <- body
}()
select {
case data := <-result:
return data, nil
case <-time.After(d):
return nil, fmt.Errorf("timeout after %v", d)
}
}
// Cancellation with context (production preferred)
func processJobs(ctx context.Context, jobs <-chan Job) {
for {
select {
case <-ctx.Done():
return
case job, ok := <-jobs:
if !ok { return }
process(job)
}
}
}Nil channel trick: a case on a nil channel is permanently disabled — it never fires. This allows you to dynamically enable and disable select cases by toggling a channel variable between nil and a real channel.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
