Go

What does this program do? (unbuffered send in main)

Question 195MediumGo 1.22 to 1.25
package main

import "fmt"

func main() {
	ch := make(chan int)
	go func() {
		for v := range ch {
			fmt.Println(v)
		}
	}()
	ch <- 1
	ch <- 2
	close(ch)
}

It prints 1 and maybe 2. The sends succeed because a receiver exists. But once the second send hands off 2, main closes the channel and returns, and returning from main kills every goroutine, possibly before the second Println runs. The unbuffered handoff guarantees the receiver got the value, not that it finished processing it.

Fix: wait for the consumer.

done := make(chan struct{})
go func() {
	defer close(done)
	for v := range ch { fmt.Println(v) }
}()
ch <- 1
ch <- 2
close(ch)
<-done

The interviewer is checking whether you know that main doesn't wait for goroutines, and that "delivered" and "processed" are different things.

More on Channels & select

All 38 Channels & select questions