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

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

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

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

Go
暮色呼如 2023-08-21 14:37:08
以這兩個片段為例使用父作用域中的 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 回答

?
FFIVE

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


查看完整回答
反對 回復(fù) 2023-08-21
  • 1 回答
  • 0 關(guān)注
  • 117 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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