Golang interface method – pointer receiver or value receiver

Recently I have been working with Golang interface.

There are lots of confusions on how to use interface in Golang, particularly how to implement the methods in interface. Should I implement pointer receiver, or value receiver? How to mutate a struct that implements an interface? Can I implement both?

Here is a sample code to clear the confusion (http://play.golang.org/p/6u6g2HM33X):

As you can see, a method in an interface can be implemented by either pointer receiver and value receiver.

In the case of pointer receiver, the pointer to the struct (*UserMutable in the example above)  implements the interface.

In the case of value receiver, the the struct itself (UserImmutable in the example above)  implements the interface.

Hope this clears confusions for people new to Golang.

Leave a Reply