What’s the difference between “

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.

Leave a Comment