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