1 回答

TA貢獻(xiàn)1797條經(jīng)驗 獲得超6個贊
chan是一個引用類型,就像切片或地圖一樣。Go 中的所有內(nèi)容都是按值傳遞的。當(dāng)您將 chan 作為參數(shù)傳遞時,它會創(chuàng)建引用相同值的引用的副本。在這兩種情況下,通道都可以從父作用域使用。但也有一些差異。考慮以下代碼:
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 關(guān)注
- 117 瀏覽
添加回答
舉報