What is the <-
operator in go language? Have seen this in many code snippets related to Go but what is the meaning of it?
"=" is assignment,just like other language. <- is a operator only work with channel,it means put or get a message from a channel. channel is an important concept in go,especially in concurrent programming.
In Go language, a channel is created using chan keyword and it can only transfer data of the same type, different types of data are not allowed to transport from the same channel. You can also create a channel using make() function using a shorthand declaration.
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)
<-
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 channelch
. 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
Receive operator
For an operand
ch
of channel type, the value of the receive operation<-ch
is the value received from the channelch
.
It receives a value from a channel. See http://golang.org/ref/spec#Receive_operator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With