du27271 2017-11-24 05:47
浏览 36
已采纳

通过迭代函数切片调用每个函数

I am trying to loop a slice of function and then invoke every function in it. However I am getting strange results. Here is my code:

package main

import (
    "fmt"
    "sync"
)

func A() {
    fmt.Println("A")
}

func B() {
    fmt.Println("B")
}

func C() {
    fmt.Println("C")
}

func main() {
    type fs func()
    var wg sync.WaitGroup
    f := []fs{A, B, C}
    for a, _ := range f {
        wg.Add(1)
        go func() {
            defer wg.Done()
            f[a]()
        }()
    }
    wg.Wait()
}

I was thinking that it will invoke function A,B and then C but my output gets only Cs.

C
C
C

Please suggest whats wrong and the logic behind it. Also how can I get desired behavior.

Go Playground

  • 写回答

2条回答 默认 最新

  • dongmiao520892 2017-11-24 06:28
    关注

    Classic go gotcha :)

    Official Go FAQ

    for a, _ := range f {
        wg.Add(1)
        a:=a // this will make it work
        go func() {
            defer wg.Done()
            f[a]()
        }()
    }
    

    Your func() {}() is a closure that closes over a. And a is a shared across all the go func go routines because for loop reuses the same var (meaning same address in memory, hence same value), so naturally they all see last value of a.

    Solution is either re-declare a:=a before closure (like above). This will create new var (new address in memory) which is then new for each invocation of go func.

    Or pass it in as parameter to the go function, in which case you pass a copy of value of a like so:

    go func(i int) {
        defer wg.Done()
        f[i]()
    }(a)
    

    You don't even need to have go routines this https://play.golang.org/p/nkP9YfeOWF for example demonstrates the same gotcha. The key here is 'closure'.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊