calling each function by iteration function slice

Issue

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

Solution

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’.

Answered By – k1m190r

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.