drus39136 2015-06-04 09:42
浏览 32
已采纳

方法的指针接收器的Go语法

In go one can define a method for a pointer receiver, as well. And Go can interpret the code syntax as follows:

In definition of the method, only writing the pointer type for the receiver is enough, inside the function definition you need not to dereference the pointer to access the very object in memory you want to access.

In function call, you do not need to call the function on a pointer type, on a reference I mean. Go can understand that you mean it.

type Box struct {
    color string
}

var b Box

Based on that what is the reason for the golang code snippets are equivalent below? Are there a different reason other than convenience or code shorthand?

Go way, but the classical C way works, as well:

func (b *Box) setColor(c string) {
    b.color = c
}
b.setColor("blue")

Classical C way:

func (b *Box) setColor(c string) {
    (*b).color = c
}
(&b).setColor("blue")
  • 写回答

1条回答 默认 最新

  • dongsilu2237 2015-06-04 09:55
    关注

    It is as you say simply shorthand:

    From the spec

    Method values:

    As with method calls, a reference to a non-interface method with a pointer receiver using an addressable value will automatically take the address of that value: t.Mp is equivalent to (&t).Mp.

    And method calls:

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100