what is the “less than followed by dash” operator in go language?

后端 未结 3 471
臣服心动
臣服心动 2021-02-03 21:45

What is the <- operator in go language? Have seen this in many code snippets related to Go but what is the meaning of it?

相关标签:
3条回答
  • 2021-02-03 21:54

    Receive operator

    For an operand ch of channel type, the value of the receive operation <-ch is the value received from the channel ch.

    It receives a value from a channel. See http://golang.org/ref/spec#Receive_operator

    0 讨论(0)
  • 2021-02-03 22:01

    You've already got answers, but here goes.

    Think of a channel as a message queue.

    If the channel is on the right of the left arrow (<-) operator, it means to dequeue an entry. Saving the entry in a variable is optional

    e <- q
    

    If the channel is on the left of the left arrow operator, it means to enqueue an entry.

    q <- e
    

    Further note about "dequeue" (receive) without storing in a variable: it can be used on a non-buffered queue to implement something like a "wait/notify" operation in Java: One coroutine is blocked waiting to dequeue/receive a signal, then another coroutine enqueues/sends that signal, the content of which is unimportant. (alternately, the sender could be blocked until the receiver pulls out the message)

    0 讨论(0)
  • 2021-02-03 22:16

    <- is used in more than one place in the language specification:

    Channel types:

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

    Receive operator:

    For an operand ch of channel type, the value of the receive operation <-ch is the value received from the channel ch. The type of the value is the element type of the channel. The expression blocks until a value is available. Receiving from a nil channel blocks forever. Receiving from a closed channel always succeeds, immediately returning the element type's zero value.

    Send statements:

    A send statement sends a value on a channel. The channel expression must be of channel type and the type of the value must be assignable to the channel's element type.

    SendStmt = Channel "<-" Expression .
    Channel  = Expression .
    

    The receive operator is also a fundamental part of the select statement

    0 讨论(0)
提交回复
热议问题