Go: Pointer to methods

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))
Advertisement
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s