0

Is it possible to resolve a string to function in golang without doing a manual match?

My use case is that I have a series of commands/requests represented as structs. I use reflection to present the values on the request struct to the user so that they can provide input parameters before I use the populate struct to run a query.

Some of the required values are uuids, where this is the case i would like to add a struct tag to define a function to call to populate a list of values e.g where my struct appears as follows:

type MyRequest struct{
    RecordID string `uuid:"RecordIDs"`
}

I would like to reflect over the struct, read the tag so that I now have a string containing "RecordIDs" (fine up to this point) and convert this to a function call - this is the bit I'm missing.

The only way I can think of to resolve the string to a function call is to provide a map lookup, e.g

funcLookup := map[string]func() ([]string, error){}

Is there another way of doing this without providing such a map

SwiftD
  • 5,769
  • 6
  • 43
  • 67
  • 1
    No, you need to map the strings to the functions you want – JimB Feb 28 '18 at 15:01
  • cool, thanks for confirming, I shall waste no more time on this - happy to close as duplicate – SwiftD Feb 28 '18 at 15:03
  • 1
    Note that you can call _methods_ by name, just not _functions_. See details in the accepted answer of the marked duplicate. – icza Feb 28 '18 at 15:03
  • @icza thats interesting - i will have a look into that, see if that makes life any easier – SwiftD Feb 28 '18 at 15:04
  • ^^ i think calling methods by name will work for me - if any reader interested in that approach google "golang reflect MethodByName" – SwiftD Feb 28 '18 at 15:07

0 Answers0