Method Sets in Go - Rules for Interface implementation

Method Sets in Go - Rules for Interface implementation


Introduction

Method sets help you to understand the rules around interface compliance. There are two types of method sets -

  • Values method sets (used with value type receiver in Go)
  • Pointer method sets (used with pointer type receiver in Go)

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.

https://go.dev/play/p/5Z9mgICItTg

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-

  1. If you implement a interface using a pointer receiver, then only pointers of that type implement the interface.
  2. If you implement a interface using a value receiver, then both pointers and values of that type implement the interface.

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!

要查看或添加评论,请登录

Akhand Agarwal的更多文章

  • Backend for frontend(BFF) pattern vs API gateway

    Backend for frontend(BFF) pattern vs API gateway

    Introduction When designing microservices, two key patterns often come into play: BFF (Backend for frontend) and API…

    6 条评论