Goroutine and channel

less than 1 minute read

This is a mini retrospect of the fundamentals of goroutine and channel in Go after getting stuck in an exercism task. The full official details can always be found in the language spec.

  • Channel is supposed to be shared between different goroutines (or your main and sub goroutines)
  • Usually at least one goroutine puts things in the channel, and at least one other consume things in it
  • When `c:=range channelXxx` is used, the loop will loop indefinitely until somebody closes the channel. That doesn’t mean you can not get out of the loop by other means, like ‘break’, ‘return’…
  • The main goroutine will exit without waiting for the completion of other goroutines, unless we use waitgroup, conditional loop or range-channel-loop in the main method to block its exit. And exit when some condition is changed.

Many of my difficulties were caused by my misunderstanding of these fundamentals, or my doubt on my understanding which was correct.

Categories: Tech