0

I have an array of strings which could be generated with different number of elemnts. And I'd like to make a map, where each string from that array will be associated with specific function. In theory, it might look like this example, but this code doesn't work of course:

package main

import "fmt"
import "strings"

var (
    Names []string {"foo", "bar", "baz"}
)

func main() {
    m := make(map[string]interface{})
    for _, name := range Names {
        fnname := strings.Title(name)
        // add function to the map
        m[name] = fnname
    }

    // exec functions store in the map
    for _, fn := range m {
        fn()
    }
}

func Foo() {
    fmt.Println("I'm foo")
}
func Bar() {
    fmt.Println("I'm bar")
}
func Baz() {
    fmt.Println("I'm baz")
}

I'm looking on reflect package, but haven't found the way how to convert name of supposed function (which is string) to the function itself.

lesovsky
  • 326
  • 2
  • 14
  • You can't get a function by its name. You can get methods though. See the marked duplicate. – icza Jan 15 '19 at 07:38
  • Thank you, one of those solutions (transforming functions to methods) is suitable for my case. – lesovsky Jan 15 '19 at 10:15

0 Answers0