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.
More Related questions...