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

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.


This is an example of a receive-only channel.

The optional <- operator specifies the channel direction, send or receive. If no direction is given, the channel is bidirectional. A channel may be constrained only to send or only to receive by conversion or assignment.

It's useful to tell the users of your API that they should only receive from that channel and never send, otherwise bad things happen. It is considered a good practice to specify the direction of your channels in public APIs. See also: Principles of designing Go APIs with channels.