dongmi1872 2018-04-20 08:52
浏览 128
已采纳

在golang中,如果其中一个方法必须具有指针接收器,是否有必要将一种类型的所有方法都更改为具有指针接收器?

I'm studying golang and I'm a little confused about defining methods on values or pointers. As mentioned in the doc:

Next is consistency. If some of the methods of the type must have pointer receivers, the rest should too, so the method set is consistent regardless of how the type is used. See the section on method sets for details.

If I have a type T, it need to implement several interfaces. One interface has method which need to use pointer receiver, and methods in another interfaces can work pretty well with value receiver. Is it necessary to change all methods in all interfaces to have pointer receivers? If so, why?

  • 写回答

3条回答 默认 最新

  • dounianluo0086 2018-04-20 09:20
    关注

    It depends :)

    Your type T has two method sets:

    • method set of receiver (t T) which is all methods defined with receiver (t T)

    • method set of receiver (t *T) which is all methods that have receiver (t *T) AND all methods that have receiver (t T)

    So if you have an interface that is satisfied by T, it is also satisfied by *T. (but not vice versa)

    Hence, if you have to add a *T receiver method to a type to satisfy an interface you do not need to change the other method receivers to *T, but you will have to be aware that now only a *T satisfies that interface and not a T and other interfaces may be satisfied for both.

    type fooer interface {
        foo()
    }
    
    type barer interface {
        bar()
    }
    
    type T struct {}
    
    func (t T)foo(){}
    
    func (t *T)bar(){}
    
    var _ fooer = T{}  // ok
    var _ barer = T{}  // NOT OK - won't compile
    var _ barer = &T{} // ok
    var _ fooer = &T{} // ok
    

    Confusing? Yes it can be. So although you don't have to change all of the methods to have a pointer receiver it's more consistent and less confusing if you do - that way you know that you are always dealing with a *T in your code - and it seems to be what most people do.

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

报告相同问题?

悬赏问题

  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)