I am trying to create an return a function in golang which has a return type of (SomeStruct, error) (standard error interface)
fn := func (args []reflect.Value) []reflect.Value {
database := mongoConnectorInstance.GetDatabase()
defer database.Session.Close()
selector := bson.M{
field : args[0].Interface(),
}
newValue := reflect.New(fieldFunctionValue.Type().Out(0))
newValueInterface := newValue.Interface()
fmt.Println(reflect.TypeOf(newValueInterface))
err := database.C(collection).Find(selector).One(newValueInterface)
secondValue := reflect.ValueOf(err)
return []reflect.Value {
newValue.Elem(),
secondValue,
}
}
resultFunctionValue := reflect.MakeFunc(fieldFunctionValue.Type(), fn)
If err returned by .One
function is null, I get address pointer error on this line, internally in golang :
panic("reflect: function created by MakeFunc using " + funcName(f) +
" returned wrong type: have " +
out[i].typ.String() + " for " + typ.String())
I have tried to change the line of secondValue assignment to :
secondValue := reflect.ValueOf((error)(nil))
in the case where err == nil
, however the problem did not go away.
If I create a dummy error struct that implements the interface error and return that, ignoring error return value has to be nil when it is really nil, then it complains that the return value by the function made by makeFunc is incorrect
Can you think of a way to solve this problem? (Except wrapping the error in a struct, and changing the return type to that struct instead )
Use this line to set secondValue
:
secondValue := reflect.ValueOf(&err).Elem()
The call ValueOf(&err)
returns a reflect.Value
with type *error
. Calling Elem()
on that value returns a reflect.Value
with type error
.
The call ValueOf(err)
returns a reflect.Value
with the type of the concrete value of err
or an invalid reflect.Value
if there is no concrete value in err
(err == nil
). Either way, the returned reflect.Value
does not have type error
.