Hi I have a question regarding method sets. In the code below I understand why line 30 gives a compilation error (variable has value semantics so cant really user pointer semantics etc). However I don’t quite understand why line 29 doesn’t throw an error. Why does the language permit calling a method with a reference of *T on a variable of type T? Code is as per below.
Hi @Sarabjit_Bhatia ,
Why does the language permit calling a method with a reference of *T on a variable of type T?
This is possible because methods with a pointer receiver are also bound to the pointer’s base type. (See Method declrarations in the Go spec.)
In other words, the dot operator in
u.notify()
accepts a pointer as well as a non-pointer on the left side.
sendNotification(u)
, on the other hand, has interface semantics that work differently.
This call
sendNotification(u)
fails because sendNotification()
expects an interface with method notify()
. Only pointer types can implement this interface, because method notify()
has a pointer receiver. Hence sendNotification(u) complains because
uis a non-pointer
uservalue, but
sendNotification(&u)` works fine. (See Method sets in the spec).
Thanks a lot for help!
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.