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

GoChannel

Go Problem Overview


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.

Go Solutions


Solution 1 - Go

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.

Solution 2 - Go

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbsView Question on Stackoverflow
Solution 1 - GoMathias DolidonView Answer on Stackoverflow
Solution 2 - GoAinar-GView Answer on Stackoverflow