第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將通道作為形式參數(shù)傳遞給閉包與使用父范圍中定義的通道之間的區(qū)別?

將通道作為形式參數(shù)傳遞給閉包與使用父范圍中定義的通道之間的區(qū)別?

Go
一只萌萌小番薯 2022-05-23 16:09:50
以這兩個片段為例使用父作用域的 out chanfunc Worker() {    out := make(chan int)    func() {        // write something to the channel    }()    return out}將 out chan 作為正式參數(shù)傳遞給閉包func Worker() {    out := make(chan int)    func(out chan int) {        // write something to the channel    }(out)    return out}我知道將參數(shù)傳遞給閉包會創(chuàng)建一個副本,并且使用父作用域中的某些東西會使用引用,所以我想知道在通過副本傳遞的情況下它在內(nèi)部是如何工作的。是否有兩個通道,一個在父范圍內(nèi),另一個副本傳遞給閉包,當(dāng)閉包中的副本寫入該值的副本時,該值的副本也在父范圍的通道中創(chuàng)建?因為我們將父作用域中的 out chan 返回給調(diào)用者,并且這些值將僅從該通道中使用。
查看完整描述

1 回答

?
BIG陽

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


查看完整回答
反對 回復(fù) 2022-05-23
  • 1 回答
  • 0 關(guān)注
  • 120 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號