以下涉及 Go 中通道的函数参数有什么区别?
What's the difference between the following function arguments involving channels in Go?
此代码在函数参数中使用 通道运算符:
func Worker(item <- chan string)
并且此代码在函数参数中没有通道运算符:
func Worker(item chan string)
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.
来自 golang 规范:https://golang.org/ref/spec#Channel_types
func Worker(item <- chan string)
这里item
是发送通道。您只能向它发送值而不能从中接收。
func Worker(item chan string)
这里item
是一个双向通道。发送和接收都可以。
您可以尝试使用此代码示例来模拟通道方向。
// 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
此代码在函数参数中使用 通道运算符:
func Worker(item <- chan string)
并且此代码在函数参数中没有通道运算符:
func Worker(item chan string)
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.
来自 golang 规范:https://golang.org/ref/spec#Channel_types
func Worker(item <- chan string)
这里item
是发送通道。您只能向它发送值而不能从中接收。
func Worker(item chan string)
这里item
是一个双向通道。发送和接收都可以。
您可以尝试使用此代码示例来模拟通道方向。
// 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