gpt4 book ai didi

go - 为什么没有为命名指针类型定义方法?

转载 作者:IT王子 更新时间:2023-10-29 01:02:43 25 4
gpt4 key购买 nike

effective Go 的文档中它指出:

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
}

然后继续提供一个指针作为接收者的例子:

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

这不矛盾吗?或者这是否意味着这是无效的:

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

虽然它看起来就像一个 typedef!

最佳答案

命名指针类型可能会导致歧义,如下所示:

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())
}

在最后一种情况下(尤其是 v3),根据当前规范,应该调用哪个 Get() 方法是不明确的。是的,没有理由不能定义方法解析,但对于已经有解决方案的东西,它是要添加到语言中的更多细节。

关于go - 为什么没有为命名指针类型定义方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31506625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com