“<-chan”和 "chan" 作为函数 return 类型有什么区别?
What's the difference between "<-chan" and "chan" as a function return type?
这里是 Golang 新手。
在功能上有区别吗
func randomNumberGenerator() <-chan int {
和
func randomNumberGenerator() chan int {
我都尝试过使用它们,它们似乎对我来说效果很好。
我在 Google IO 2012 上看到 Rob Pike(Go 的创造者之一)在他的 Go Concurrency Patterns 演讲中使用了前者。我还在 Go 的官方网站上看到了它的使用。既然可以省略,为什么还要添加 2 个额外字符 ("<-")?我尝试在网上寻找差异,但找不到。
这是一个 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.
告诉 API 的用户他们应该 只 从那个频道接收并且 从不 发送是很有用的,否则会发生坏事。在 public API 中指定频道的方向被认为是一种很好的做法。另见:Principles of designing Go APIs with channels.
两者都确实有效。但是一个会更有约束力。箭头指向远离 chan
关键字的表单意味着 returned 通道只能由客户端代码拉出。不允许推送:推送将由随机数生成器函数完成。相反,还有第三种形式,箭头指向 chan
,这使得所述通道对客户端只写。
chan // read-write
<-chan // read only
chan<- // write only
这些添加的约束可以改善意图的表达并收紧类型系统:尝试将内容强制放入只读通道将导致编译错误,因此尝试从只写通道读取.这些约束可以用 return 类型表示,但它们也可以是参数签名的一部分。比如:
func log(<-chan string) { ...
你可以知道,仅通过签名,log
函数将使用通道中的数据,而不向其发送任何数据。
这里是 Golang 新手。
在功能上有区别吗func randomNumberGenerator() <-chan int {
和
func randomNumberGenerator() chan int {
我都尝试过使用它们,它们似乎对我来说效果很好。
我在 Google IO 2012 上看到 Rob Pike(Go 的创造者之一)在他的 Go Concurrency Patterns 演讲中使用了前者。我还在 Go 的官方网站上看到了它的使用。既然可以省略,为什么还要添加 2 个额外字符 ("<-")?我尝试在网上寻找差异,但找不到。
这是一个 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.
告诉 API 的用户他们应该 只 从那个频道接收并且 从不 发送是很有用的,否则会发生坏事。在 public API 中指定频道的方向被认为是一种很好的做法。另见:Principles of designing Go APIs with channels.
两者都确实有效。但是一个会更有约束力。箭头指向远离 chan
关键字的表单意味着 returned 通道只能由客户端代码拉出。不允许推送:推送将由随机数生成器函数完成。相反,还有第三种形式,箭头指向 chan
,这使得所述通道对客户端只写。
chan // read-write
<-chan // read only
chan<- // write only
这些添加的约束可以改善意图的表达并收紧类型系统:尝试将内容强制放入只读通道将导致编译错误,因此尝试从只写通道读取.这些约束可以用 return 类型表示,但它们也可以是参数签名的一部分。比如:
func log(<-chan string) { ...
你可以知道,仅通过签名,log
函数将使用通道中的数据,而不向其发送任何数据。