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

huangapple go评论88阅读模式
英文:

Go Syntax of Pointer Receivers of a Method

问题

在Go语言中,可以为指针接收器定义方法。Go语言可以按照以下方式解释代码语法:

在方法的定义中,只需为接收器写入指针类型即可,在函数定义内部,您无需解引用指针即可访问内存中的对象。

在函数调用中,您不需要在指针类型上调用函数,我是指在引用上。Go语言可以理解您的意思。

type Box struct {
    color string
}

var b Box

基于此,下面的golang代码片段等效的原因是什么?除了方便和代码简写之外,还有其他不同的原因吗?

Go语言的方式,但经典的C方式也可以工作:

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

经典的C方式:

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

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

得分: 2

这只是简单的速记,正如你所说:

根据规范:

方法值

> 与方法调用一样,对于使用可寻址值的指针接收器的非接口方法的引用将自动获取该值的地址:t.Mp 等同于 (&t).Mp。

以及方法调用

> 如果 x 的方法集包含 m 并且参数列表可以分配给 m 的参数列表,则方法调用 x.m() 是有效的。如果 x 是可寻址的并且 &x 的方法集包含 m,则 x.m() 是 (&x).m() 的速记

英文:

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

huangapple
  • 本文由 发表于 2015年6月4日 17:42:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/30640392.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定