Golang: Why is the selector for pointers illegal after comparison?

I read the specification about selectors: https://golang.org/ref/spec#Selectors

enter image description here

Why q.M0() invalid. So far p.M0() valid and q=p . Very strange to me.

Relevant source code:

 type T0 struct { x int } func (*T0) M0() type T1 struct { y int } func (T1) M1() type T2 struct { z int T1 *T0 } func (*T2) M2() type Q *T2 var t T2 // with t.T0 != nil var p *T2 // with p != nil and (*p).T0 != nil var q Q = p p.M0() // ((*p).T0).M0() M0 expects *T0 receiver q.M0() // (*q).M0 is valid but not a field selector 
+6
source share
1 answer

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?

+7
source

Source: https://habr.com/ru/post/1012648/


All Articles