Golang channels - quit channel

Sometimes you may want to break your program running inside goroutine from other goroutine or simply from main function. Below You can see My simple implementation of go quit channel.

package main

import (

func main() {
	quit := make(chan bool)
	go func() {
		for {
			select {
			case <-quit:
				time.Sleep(time.Millisecond * 100)

	// Do stuff

	// Quit goroutine
	quit <- true

Run it on play.golang.org

Code Summary

In context of communicating from external goroutines:

  • Use select to read from multiple channels (in our example We only want to break infinite loop)
  • default is always run when there is no value from channel

Want More?

If you like My Go basics series feel free to read more at Go Basics Series

comments powered by Disqus