通过对象而不是指向它的指针调用一个指针接收器的方法? [英] Calling a method with a pointer receiver by an object instead of a pointer to it?
问题描述
v
是顶点
和比例
是一个指向 Vertex
的指针的方法。那么为什么 v.Scale(10)
没有错,因为 v
不是指向顶点
对象? package main
import(
fmt
数学
)
类型顶点结构{
X,Y float64
}
func(v顶点)Abs()float64 {
return math.Sqrt(vX * vX + vY * vY)
}
func(v * Vertex)Scale(f float64){
vX = vX * f
vY = vY * f
}
func main(){
v:= Vertex {3,4}
v.Scale(10)
fmt.Println(v.Abs())
}
方法调用
xm()
在 包含m $ c $的方法集合
/ spec#Method_setsrel =noreferrer>方法集合 c>并且参数列表可以被分配给m
的参数列表。如果x
是寻址和& x
的方法集包含m
,xm()
是(& x).m()
的缩写。
编译器发现 Scale()
有一个指针接收器,而且 v
是可寻址的它是一个局部变量),所以 v.Scale(10)
将被解释为(& v).Scale(10)
这只是规范提供的许多便利之一,所以源代码可以保持干净。
v
is an object of Vertex
, and Scale
is a method for a pointer to Vertex
. Then why is v.Scale(10)
not wrong, given that v
isn't a pointer to a Vertex
object? Thanks.
package main
import (
"fmt"
"math"
)
type Vertex struct {
X, Y float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
func main() {
v := Vertex{3, 4}
v.Scale(10)
fmt.Println(v.Abs())
}
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()
.
The compiler sees that Scale()
has a pointer receiver and also that v
is addressable (as it is a local variable), so v.Scale(10)
will be interpreted as (&v).Scale(10)
.
This is just one of the many conveniences the spec offers you so the source code can remain clean.
这篇关于通过对象而不是指向它的指针调用一个指针接收器的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!