dqv84329 2014-08-13 02:52
浏览 38
已采纳

指针上定义的方法仍然可以用值调用

The "Effective Go" documentation says the following.

The rule about pointers vs. values for receivers is that value methods can be invoked on pointers and values, but pointer methods can only be invoked on pointers.

http://tip.golang.org/doc/effective_go.html#pointers_vs_values

As such, if I define a method like the following, wouldn't it not be callable with a value?

func (self *someStruct) Change(newNum int) {
    self.propertyOne = newNum
}

However, the following still seems to work.

structInstance := &someStruct{
    propertyOne: 41,
}
(*structInstance).Change(456)

Why?

Is it converting the value (*structInstance) back into an address/pointer for the Change call?

How do I ensure that some instance of a type cannot call a method defined on the pointer (like Change)?

Go Playground Demo

http://play.golang.org/p/azbpp_djlG

  • 写回答

2条回答 默认 最新

  • dongshiran7000 2014-08-13 03:24
    关注

    From the language specification:

    A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m. If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m()

    In your example, there is no Change method in (*structInstance)'s method set, but it is addressable and the method exists in &(*structInstance)'s method set, so the call is interpreted as (&(*structInstance)).Change(456), or more simply structInstance.Change(456).

    The only way to prevent this behaviour would be to also define the Change method on someStruct, perhaps making it panic. That's not ideal though, since it will only tell you about the problem at runtime. It would be less confusing to structure your program so that the use of this shorthand doesn't actually matter.

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

报告相同问题?

悬赏问题

  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄