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.