gpt4 book ai didi

go - 将 channel 作为形式参数传递给闭包与使用父范围中定义的 channel 之间的区别?

转载 作者:行者123 更新时间:2023-12-01 22:15:06 25 4
gpt4 key购买 nike

以这两个片段为例

  • 使用父作用域中的 out chan
  • func 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
    }

    我知道将参数传递给闭包会创建一个副本,并且使用父作用域中的某些东西会使用引用,所以我想知道在通过副本传递的情况下它在内部是如何工作的。是否有两个 channel ,一个在父范围内,另一个副本传递给闭包,当闭包中的副本写入该值的副本时,该值的副本也在父范围的 channel 中创建?因为我们将父作用域中的 out chan 返回给调用者,并且这些值将仅从该 channel 中使用。

    最佳答案

    chan是一个引用类型,就像 slice 或映射一样。 go 中的所有内容都是按值传递的。当您将 chan 作为参数传递时,它会创建引用相同值的引用副本。在这两种情况下, channel 都可以从父作用域中使用。但是有几个不同之处。考虑以下代码:

    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

    关于go - 将 channel 作为形式参数传递给闭包与使用父范围中定义的 channel 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60779689/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com