Reputation: 103
This code with the channel operator in the function argument:
func Worker(item <- chan string)
And this code without the channel operator in the function argument:
func Worker(item chan string)
Upvotes: 0
Views: 69
Reputation: 337
You can try this code example to simulate channel direction.
// func Worker(item <- chan string) # Send or Receive
// func Worker(item chan string) # Bidirectional
func sendOrRecvFunc(item <-chan string, msg *string) {
*msg = <- item // send
}
func bidirectionalFunc(item chan string, msg string) {
item <- msg // receive
}
func main() {
// e.g Send or Receive
var msg1 string
item1 := make(chan string,1)
item1 <- "message1" // receive
sendOrRecvFunc(item1,&msg1)
fmt.Println(msg1)
//---------------------------------------------
// e.g Bidirectional
item2 := make(chan string,1)
bidirectionalFunc(item2,"message2")
msg2 := <- item2 // send
fmt.Println(msg2)
}
// Output:
message1
message2
Upvotes: 0
Reputation: 665
func Worker(item <- chan string)
Here item
is a send channel. You can only send value to it can't receive from it.
func Worker(item chan string)
Here item
is a bidirectional channel. Both send and receiving is possible.
Upvotes: 1
Reputation: 8222
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.
From golang spec: https://golang.org/ref/spec#Channel_types
Upvotes: 5