为什么没有为命名指针类型定义任何方法?
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!
在有效的Go 它指出: p>
正如我们在ByteSize上看到的那样,可以为任何命名类型定义方法 (除了 指针... p> blockquote>
类型ByteSlice [] byte func(切片ByteSlice)Append(数据[] byte)[] byte { / /正文与上面完全相同 } code> pre>
然后继续提供一个带有指针作为接收器的示例: p>
func(p * ByteSlice)追加(数据[] byte){ slice:= * p //上面的内容,没有返回。 * p = slice } pre>
不是矛盾的吗?或者这意味着这是无效的: p>
type ByteSlice [] byte type Pb * ByteSlice func(p Pb)追加(数据[] byte)[] byte { } code> pre>
尽管它看起来像typedef! p> div>
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.
A named type that is a pointer isn't the same as a pointer to a named type.
This is what the language reference says:
That parameter section must declare a single parameter, the receiver. Its type must be of the form T or *T (possibly using parentheses) where T is a type name. The type denoted by T is called the receiver base type; it must not be a pointer or interface type and it must be declared in the same package as the method.
That's clear enough: if T denotes a pointer type, then you can't use it as a method receiver.
Note the careful language of the reference 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 the type). That's different from the phrase "The type denoted by T", where it's talking about the type that T names (that is, what the type "denotes").