1 回答

TA贡献1797条经验 获得超6个赞
chan是一个引用类型,就像切片或地图一样。Go 中的所有内容都是按值传递的。当您将 chan 作为参数传递时,它会创建引用相同值的引用的副本。在这两种情况下,通道都可以从父作用域使用。但也有一些差异。考虑以下代码:
ch := make(chan int)
var wg sync.WaitGroup
wg.Add(1)
go func() {
ch <- 1
ch = nil
wg.Done()
}()
<-ch // we can read from the channel
wg.Wait()
// ch is nil here because we override the reference with a null pointer
与
ch := make(chan int)
var wg sync.WaitGroup
wg.Add(1)
go func(ch chan int) {
ch <- 1
ch = nil
wg.Done()
}(ch)
<-ch // we still can read from the channel
wg.Wait()
// ch is not nil here because we override the copied reference not the original one
// the original reference remained the same
- 1 回答
- 0 关注
- 103 浏览
添加回答
举报