2015-08-10 13:04
浏览 212

“ <-chan”和“ chan”作为函数返回类型有什么区别?

Golang newbie here.

Is there a functional difference between

func randomNumberGenerator() <-chan int {


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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dounue1965
    dounue1965 2015-08-10 13:10

    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.

    点赞 评论
  • dongye1912
    dongye1912 2015-08-10 13:08

    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.

    点赞 评论