Go, as a language, makes it very easy to work in parallel on data through its use of go routines (more info on go routines here). However, one of the tricky parts about using go routines is a) to know when they are finished and b) to pass data back from the go routine. Channels make both of these things possible.
In this post we’re only going to look at a basic use case of channels. In the code below we ask the
work() function to run on a separate go routine and when it’s finished pass back the string ‘done’ - which will then be printed to screen.
You’ll notice that channels are defined with the
chan keyword and can be made with
In this example, the work function also explicitly states which way the channel it expects will send data. So
chan<- will accept data passed into it, and
<-chan will expect a channel to pass data out of.
In exactly the same way we can achieve syncronization between go routines by using a channel but only sending back a bool to say it’s complete.