1 回答

TA貢獻(xiàn)1859條經(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)注
- 120 瀏覽
添加回答
舉報