mardi 28 mars 2017

Check if a reflect.Type does implements another reflect.Type

Heys guys, I'm creating a library in golang for my company. I want the client pass to us a callback with func(t ) error; Since there's no generics in Go, I'm trying to check the arguments and return type through reflection.

But I'm failling right now. Any help?

func check(F interface{}) bool {
    errorInterface  := reflect.TypeOf((*error)(nil)).Elem()
    if tpFunc := reflect.TypeOf(Func); tpFunc.Kind() != reflect.Func {
        return false
    } else if tpFunc.NumIn() != 1 || tpFunc.NumOut() != 1 {
        return false
    } else if tpArg := tpFunc.In(0); tpArg.Kind() != reflect.Ptr || tpArg.Elem().Kind() != reflect.Struct {
        return false
    } else if tpRet := tpFunc.Out(0); tpRet.Implements(errorInterface)  {
        return false
    }
    return true
}



type T0 struct {
   A int64
   B float
}

func F0(t *T0) error {
  ...
}

func F1(t *T0) int {
  ...
}





Aucun commentaire:

Enregistrer un commentaire