为什么具有指针接收器的方法在接收到值时仍然工作? [英] Why does a method with a pointer receiver still work when it receives a value?
问题描述
我刚刚在 Go Tour的练习51中玩法。该解释声明 Scale
方法在接收顶点
时不起作用,而不是指向 Vertex
。
然而,当我更改声明 v:=& Vertex {3,4}
到 v:=顶点{3,4}
在 main
是缺少的&
来标记指针。为什么 Scale
code>改变它收到的变量,即使变量不是一个指针?
它不会接收 一个值。 Go是强类型的,所以如果指定了T指针,那么指向T( * T
)的指针是唯一可以作为这种类型位置的值的选项。
魔术是在编译器中有效地重写你的代码在某些 conditions :
方法调用
xm()如果
x
(的类型)的方法集包含m
和参数列表,则code>可以分配给m
的参数列表。如果x
是可寻址的,& x的方法集包含m
,xm() code>是
(& x).m()
的缩写:
相关:方法集
I was just playing with Exercise 51 in the Tour of Go. The explanation claims the Scale
method has no effect when it receives a Vertex
instead of a pointer to a Vertex
.
Yet when I change the declaration v := &Vertex{3, 4}
to v := Vertex{3, 4}
in main
the only change in the output is the missing &
to mark the pointer.
So why does Scale
change the variable it receives even if the variable isn't a pointer?
It does not "receive" a value. Go is strongly typed, so if somewhere a pointer to T is prescribed, a pointer to T (*T
) is the only option which can happen as a value for such typed place.
The "magic" is in the compiler which effectively "rewrites" your code under certain conditions:
A method call
x.m()
is valid if the method set of (the type of)x
containsm
and the argument list can be assigned to the parameter list ofm
. Ifx
is addressable and &x's method set containsm
,x.m()
is shorthand for(&x).m()
:
Related: Method sets
这篇关于为什么具有指针接收器的方法在接收到值时仍然工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!