Signaling channel with chan struct{}

suggest change

Sometimes you don’t want to send a value over a channel but use it only as a way to signal an event.

In those cases use chan struct{} to document the fact that the value sent over a channel has no meaning.

Signaling channel is often used as a way to tell goroutines to finish.

func worker(ch chan int, chQuit chan struct{}) {
	for {
		select {
		case v := <-ch:
			fmt.Printf("Got value %d\n", v)
		case <-chQuit:
			fmt.Printf("Signalled on quit channel. Finishing\n")
			chQuit <- struct{}{}
			return
		}
	}
}
func main() {
	ch, chQuit := make(chan int), make(chan struct{})
	go worker(ch, chQuit)
	ch <- 3
	chQuit <- struct{}{}

	// wait to be signalled back by the worker
	<-chQuit
}
Got value 3
Signalled on quit channel. Finishing

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents