Why aren't methods defined for the named types of pointers?

The documentation for effective Go says:

As we saw with ByteSize, methods can be defined on any named type (except pointer ...

type ByteSlice []byte
func (slice ByteSlice) Append(data []byte) []byte {
  // Body exactly the same as above
}

      

Then the following is an example with a pointer as a destination:

func (p *ByteSlice) Append(data []byte) {
  slice := *p
  // Body as above, without the return.
  *p = slice
}

      

Doesn't that contradict? Or it means it is not correct:

type ByteSlice []byte
type Pb *ByteSlice
func (p Pb) Append(data []byte) []byte {
} 

      

Although it looks just like a typedef!

+3


source to share


2 answers


Named pointer types can lead to the following ambiguities:

type T int 

func (t *T) Get() T { 
    return *t + 1 
} 

type P *T 

func (p P) Get() T { 
    return *p + 2 
} 

func F() { 
    var v1 T 
    var v2 = &v1 
    var v3 P = &v1 
    fmt.Println(v1.Get(), v2.Get(), v3.Get()) 
}

      



In the latter case (esp. v3

), It is ambiguous for the current specification which method Get()

should be called. Yes, there is no reason why the resolution of a method cannot be determined, but this is another detail to add to the language that already has a solution.

+2


source


A named type that is a pointer is not the same as a pointer to a named type.

Here's what the language says:

This parameter section must declare a single parameter, the sink. Its type must be T or * T (possibly using parentheses) where T is the type name. The type denoted by T is called the sink base type; it does not have to be a pointer or an interface type, and it must be declared in the same package as the method.



This is clear enough: if T denotes a pointer type, then you cannot use it as a method receiver.

Note the careful referencing language here: the phrase "Its type must be of the form T or T *" refers to the syntax level specification of the method receiver (that is, the "form" of that type). This is different from the phrase "Type denoted by T" where it is speaks of the type that T names (that is, what type denotes ")".

+2


source







All Articles