vendredi 7 juillet 2017

Reflect over Interface in Golang

I have some structs in Go, they implement a common method, so I created an interface for it (Because in some methods I need to receive an element of the type of the interface).Basically I have something like:

type Model interface {
    CommonMethod() string
}

Then I have something like 10 struct that implements that CommonMethod, for example:

type Contact struct {
    ...Some fields
}

func (Contact) CommonMethod() string {
    return "Something"
}

Until here everything is ok. Then I have a generic method that will receive 2 instances of Model, the proptotype for this function is:

func MyFunction(NewObject Model,PreviousObject Model)

In that function I need to compare the fields: name of the fields and values between the 2 objects. I am trying to make it using Reflect but if I use reflect.ValueOf() I only get the value of the attributes and I don't see any way to get the name. So, is there a way that I can get the struct that comes inside the Model interface so then I can use reflect.TypeOf()?





Aucun commentaire:

Enregistrer un commentaire