我只是在玩 Exercise 51 in the Tour of Go .该解释声称 Scale
方法在接收到 Vertex
而不是指向 Vertex
的指针时无效。
然而,当我在 main
中将声明 v := &Vertex{3, 4}
更改为 v := Vertex{3, 4}
> 输出中唯一的变化是缺少标记指针的 &
。
那么为什么 Scale
会更改它接收到的变量,即使该变量不是指针?
最佳答案
它不“接收”一个值。 Go 是强类型的,因此如果在某处规定了指向 T 的指针,则指向 T (*T
) 的指针是唯一可以作为此类类型位置的值发生的选项。
“魔法”在编译器中,它在某些 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()
:
相关:Method sets
关于pointers - 为什么带有指针接收器的方法在接收到值时仍然有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17996771/