vendredi 23 décembre 2016

Returning error value in reflect.MakeFunc

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 )





Aucun commentaire:

Enregistrer un commentaire