Created
October 5, 2016 16:51
-
-
Save geoffhendrey/be3a6be0adf2ca555ae61355363abe26 to your computer and use it in GitHub Desktop.
How to get an actual instance out of a Go/Golang reflect.Value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Author Geoffrrey Hendrey | |
//Here we dynamically invoke a method, passing the method the input, whose type we don't know. We know the method returns two things, a value and an errror. | |
//(multiple return values). This code shows how we grab the error, which | |
//is the second return value of the method, check it it is not nil, and if not nil type-assert it to an actual error (line 11). They key is | |
//on line 11 where we extract the interface() from the errReflect, which is reflect.Value. Once we have an interface{} we can do the type-assertion. | |
func invokeMethod(method reflect.Value, input interface{}) (resp interface{}, err error) { | |
in := []reflect.Value{reflect.ValueOf(input)} | |
returnValuesFromClientCall := method.Call(in) | |
errReflect := returnValuesFromClientCall[1] //this is the error return value from the call above | |
if !errReflect.IsNil() { //if there was an error | |
ifc := errReflect.Interface() | |
err := ifc.(error) | |
log.Errorf("method call returned error: %s", err.Error()) | |
return nil, err | |
} | |
return returnValuesFromClientCall[0].Interface(), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment