Go: Pointer to methods
Sometimes I need a pointer to a method that is not bound to an explicit object.
Method pointers are just function pointers where the first argument is the type.
Imagine we have a Pet type with a Speak method:
type Pet interface {
Speak() string
}
Here’s how we would declare, assign, and invoke the pointer
var fp func(Pet) string
fp = Pet.Speak
pet := GetPetFromSomewhere()
fmt.Sprintf("The pet says: %s\n", fp(pet))