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 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛