通道作为参数,为什么不用星号呢?

huangapple go评论77阅读模式
英文:

Channel as parameter, why not an asterisk?

问题

当我将一个通道作为参数传递给函数并在函数结束时关闭它时,我不需要在通道前面加上*来引用主函数范围内的通道。但是当我要设置一个WaitGroup为done(wg.Done())时,我必须这样做,为什么会这样呢?

英文:

When I pass a channel as a parameter to close it at the end of the function, I don't need to put * before it to refer to the channel in the main-function scope. But when I'm supposed to set a WaitGroup to done (wg.Done()) I have to so, why is that?

答案1

得分: 2

这是因为在内部,chan 是由指针构成的结构体。你不需要发送一个指针给它。相反,sync.WaitGroup 是一个经典的结构体。

type WaitGroup struct {
    state1 [12]byte
    sema   uint32
}

它的所有方法都是使用指针接收器声明的,所以你需要在不同的作用域中传递一个指针来使用它。

英文:

That's because internally, the chan is somewhat a struct made of pointers. You don't need to send a pointer to it. On contrary, the sync.WaitGroup is a classical struct

type WaitGroup struct {
    state1 [12]byte
    sema   uint32
}

for whose all methods are declared with a pointer receiver, so you need to pass a pointer to it around to use it in different scopes.

答案2

得分: 0

在Go语言中,chan是一种语言原语,而sync.WaitGroup是一个结构体。由于Go通过值传递参数,WaitGroup将被作为一个副本传递,而chan将被传递为一个类似于interface的东西,它被实现为一个包含指向实现细节的指针的元数据的原始类型。

英文:

In Go, chan is a language primitive, and sync.WaitGroup is a struct. Because Go passes parameters by value the WaitGroup would be passed as a copy, and the chan would be passed like an interface which is implemented as a primitive type with metadata including a pointer to the implementation details.

huangapple
  • 本文由 发表于 2016年4月5日 23:55:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/36431355.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定