Method Sets in Go - Rules for Interface implementation
Akhand Agarwal
Software Engineer | Allen | Ex- Zomato, Fi | Competitive Programmer ???? | Building scalable back-end applications
Introduction
Method sets help you to understand the rules around interface compliance. There are two types of method sets -
Importance of Method sets and common error while implementing a Interface
Let's look at the code below. This code is expected to compile, but it doesn't.
On compiling, this program will throw the below error
./prog.go:21:19: cannot use u (variable of type user) as notifier value in argument to sendNotification: user does not implement notifier (method notify has pointer receiver)
Go build failed.
To understand why values of type user don't implement the interface when an interface is implemented with pointer receiver, you need to understand what method sets are. Method sets define set of methods that are associated with values or pointers of a given type. The type of receiver used will determine whether a method is associated with a value, pointer or both.
Method sets Rules
Method Receivers Values
-------------------------------------
(t T) T and *T
(t *T) *T
It says-
This is the reason that in above program, since we have notify method with pointer receiver, passing a value of user as u doesn't implement the interface.
Conclusion
We discussed the Method Sets along with a program which shows it's importance and common errors. If you want to know why this restriction, you need to deep dive into interface and Go's type system. The answer comes from the fact that it's not always possible to get the address of a value.
Keep Learning!