Golang / GoLang Concurrency Mastery Interview Questions
When should a channel carry 'chan struct{}' versus a typed value, and why is close() used for broadcast?
chan struct{} is the Go idiom for pure signalling — when the fact that something occurred matters, but no data needs to be transferred. struct{}{} has zero size (no memory allocated for the value), and using it explicitly communicates 'this is a signal only'.
// chan struct{} — pure event signal (no payload)
done := make(chan struct{})
go func() {
doWork()
close(done) // broadcast: no value needed
}()
<-done // wait for signal
// Buffered chan struct{} as semaphore (acquire/release)
sem := make(chan struct{}, 10)
sem <- struct{}{} // acquire
<-sem // release
// chan bool — avoid for signals (true vs false ambiguity)
// What does 'false' mean? Failure? Not-yet? Done? Confusing.
// chan T — use when data has semantic meaning
results := make(chan int, 100) // carries computed results
errors := make(chan error, 10) // carries error values
// Broadcast via close: O(1), unblocks ALL receivers
ready := make(chan struct{})
go func() {
initialize()
close(ready) // all waiting goroutines unblock simultaneously
}()
for i := 0; i < 5; i++ {
go func() {
<-ready // all 5 unblock at the instant close() is called
doPostInit()
}()
}
// struct{} size verification
fmt.Println(unsafe.Sizeof(struct{}{})) // 0 bytes
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...
