I need to know if either the struct or the pointer to that struct implements a given interface.
// You can edit this code!
// Click here and start typing.
package main
import "fmt"
func main() {
var a A = A{
i: 5,
}
Serialize(a)
Serialize(&a)
}
type Serializable interface {
//Serialize() string
//Deserialize(string)
Serializebyte() []byte
Deserializebyte(b []byte) (bytesRead int)
}
type A struct {
i int
}
func (*A) Serializebyte() []byte {
return []byte{0x00}
}
func (*A) Deserializebyte(b []byte) (bytesRead int) {
return 0
}
func Serialize(objInt interface{}) []byte {
// this doesn't work
switch v := (objInt).(type) {
case Serializable:
fmt.Printf("I'm Serializable
")
return v.Serializebyte()
}
fmt.Printf("I'm not Serializable
")
return []byte{0x00}
}
// this other way also dont work
func Serialize2(objInt interface{}) []byte {
// this doesn't work
_, isSerializable := objInt.(Serializable)
if isSerializable{
fmt.Printf("I'm Serializable
")
return objInt.(Serializable).Serializebyte()
}
fmt.Printf("I'm not Serializable
")
return []byte{0x00}
}
// Stdout:
// I'm not Serializable
// I'm Serializable
Edit: You can run the code above to see what I mean.
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.