dtbsezxw28056 2015-07-19 22:31
浏览 58
已采纳

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

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!

  • 写回答

2条回答 默认 最新

  • duanfen1312 2015-07-19 23:08
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分