Home > Mobile >  Calling function names from a slice and return a value
Calling function names from a slice and return a value

Time:02-20

I want to call a number of function names stored in a slice. The code snippet below works so far but I need to return a value from those functions. Unfortunately I don't get it to work because I don't know to to call those functions and store the return value. Any ideas?

This is the code I'm currently working on:

package main

func A(x int) int {
    return x   1
}

func B(x int) int {
    return x   2
}

func C(x int) int {
    return x   3
}

func main() {
    x := 10
    type fs func(x int) int

    f := []fs{A, B, C}

    fns := make([]func(), 3)

    for a, _ := range f {
        a := a
        fns[a] = func() {
            f[a](x)
        }
    }

    for _, f := range fns {
        f()
    }

}

Go Playground

CodePudding user response:

You have call it...

for a, _ := range f {
        a := a
        fns[a] = func() {
            f[a](x)        // in this
        }
    }

here is the playground

  •  Tags:  
  • go
  • Related