Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no methods defined for named pointer types?

Tags:

go

In the documentation for effective Go it states:

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

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

It then goes on to provide an example with a pointer as receiver:

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

Doesn't that contradict ? Or does it mean that this isn't valid:

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

Though it looks just like a typedef!

like image 697
Sridhar Avatar asked Feb 10 '23 13:02

Sridhar


1 Answers

Named pointer types could lead to ambiguities like so:

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 last case (esp. v3) per the current spec, it's ambiguous which Get() method should be called. Yes, there's no reason that the method resolution couldn't be defined, but it's one more detail to add to the language for something that already has a solution.

like image 164
JimB Avatar answered Feb 13 '23 03:02

JimB