Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling function names from a slice and return a value

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have call it…

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

here is the playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading