Why q.M0() invalid. So far p.M0() valid and q=p . Very strange to me.
q initialized as var q Q = p , but this does not mean that they are equal. assignment is valid because it does not violate assignability , but type q is different from type p .
Type q is q (where type Q *T2 ), and type p is *T2 .
In Go, methods are of a specific type. When you do this:
type Q *T2
It creates a new type called q ( *T2 , which is its base type). The new type will have 0 methods, it will not "inherit" any methods from *T2 , so q.M0() will be a compile-time error:
q.M0 undefined (type Q has no field or method M0)
Note:
You can still find this strange, because M0() declared as follows:
func (*T0) M0()
It has a receiver *T0 , therefore it is of type *T0 , but type p is *T2 , therefore *T2 should not have this method M0() , and therefore p.M0() must also be disabled. But T2 is a structure that implements *T0 , so the *T0 methods are advancing and they will be in the T2 method .
Also see this related question: Golang: Why is the selector for pointers illegal after comparison?
source share