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
- Q193What does this print? (select with a closed channel and a nil channel)
- Q194What causes "fatal error: all goroutines are asleep - deadlock!" and when does Go fail to detect a deadlock?
- Q196How does
for rangeover a channel work, and what are its pitfalls? - Q197What are directional channel types and why use them?
- Q198How do you implement a timeout on a channel operation? Compare
time.After,time.NewTimer, andcontext. - Q199Does
time.Afterin a loop leak memory? How did Go 1.23 change this?