What's the difference between "<-chan" and "chan" as a function return type?

Abs picture Abs · Aug 10, 2015 · Viewed 7.9k times · Source

Golang newbie here.

Is there a functional difference between

func randomNumberGenerator() <-chan int {

and

func randomNumberGenerator() chan int {

I've tried using both and they seem to work fine for me.

I've seen the former used by Rob Pike (one of Go creators) in his Go Concurrency Patterns talk at Google IO 2012. I've also seen it used in Go's official website. Why add 2 extra characters ("<-") when you can omit it? I've tried looking for the difference on the web, but couldn't find it.

Answer

Mathias Dolidon picture Mathias Dolidon · Aug 10, 2015

Both will work indeed. But one will be more constraining. The form with the arrow pointing away from the chan keyword means that the returned channel will only be able to be pulled from by client code. No pushing allowed : the pushing will be done by the random number generator function. Conversely, there's a third form with the arrow pointing towards chan, that makes said channel write-only to clients.

chan   // read-write
<-chan // read only
chan<- // write only

These added constraints can improve the expression of intent and tighten the type system : attempts to force stuff into a read-only channel will leave you with a compilation error, and so will attempts to read from a write-only channel. These constraints can be expressed in the return type, but they can also be part of the parameter signature. Like in :

func log(<-chan string) { ...

There you can know, just by the signature, that the log function will consume data from the channel, and not send any to it.