mercredi 6 février 2019

How to know if a struct or pointer to struck implements an interface

I need to know if either the struct or the pointer to that struct implements a given interface.

    type Serializable interface {
      //Serialize() string
      //Deserialize(string)

      Serializebyte() []byte
      Deserializebyte(b []byte) (bytesRead int)
    }

    type A struct {
      i int
    }

    func (*A) Serializebyte() []byte{
      // do stuf
    }

    func (*A) Deserializebyte(b []byte) (bytesRead int) {
      // do stuf
    }

    func Serialize(objInt interface{}) []byte {
      // this doesn't work 
      switch (objInt).(type) {
      case Serializable:
        return objInt.(Serializable).Serializebyte()
      }


      // do stuf on object that do not implement Serializebyte
    }

Because (*A) implements Serializable not A, the assertion above does not pass but I want to know if either (*A) implements Serializable or A implements it.

Why do I want that? Because if I can do that, the programmers do not need to know how Serializable works. If not the programers should always need to pass a pointer to Serializable and implement Serializable in the struct pointer rather than the struct itself.





Aucun commentaire:

Enregistrer un commentaire