英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论