mardi 12 juillet 2022

How to convert string to func using reflect.MakeFunc?

I'm trying to create a function from a string value, this code returns a function however when calling StringToFunc("funcB") a memory address is returned. Ex: 0x1092880

func StringToFunc(inputString string) interface{} {
    funcType, funcValue := reflect.TypeOf(func() {}), reflect.ValueOf(inputString)

    return reflect.MakeFunc(funcType, func(input []reflect.Value) []reflect.Value {
        newFunc := funcValue.Call(input)
        return newFunc
    }).Interface()
}

Ultimately I'm trying to create a function for every element in a Map, constructing the function using the string value assigned to the key.

Example map is "funcB":"funcB" to type map[string]interface{} using StringToFunc() which returns map[funcB:0x1092880].





Aucun commentaire:

Enregistrer un commentaire