亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

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

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

Go
暮色呼如 2023-08-21 14:37:08
以這兩個片段為例使用父作用域中的 out chanfunc Worker() {    out := make(chan int)    func() {        // write something to the channel    }()    return out}將 out chan 作為閉包的正式參數傳遞func Worker() {    out := make(chan int)    func(out chan int) {        // write something to the channel    }(out)    return out}我知道將參數傳遞給閉包會創建該副本的副本,并使用父作用域中的某些內容使用引用,所以我想知道在傳遞副本的情況下,它在內部如何工作。是否有兩個通道,一個在父作用域中,另一個副本傳遞給閉包,并且當閉包中的副本寫入到該值的副本時,也會在父作用域的通道中創建該值的副本嗎?因為我們將父范圍中的 out chan 返回給調用者,并且這些值將僅從該通道消耗。
查看完整描述

1 回答

?
FFIVE

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


查看完整回答
反對 回復 2023-08-21
  • 1 回答
  • 0 關注
  • 119 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號