Tim*_*Tim 5 methods pointers function call go
v是指针的对象Vertex,并且Scale是指针的方法Vertex.那么为什么v.Scale(10)没有错,因为它v不是指向Vertex对象的指针?谢谢.
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())
}
Run Code Online (Sandbox Code Playgroud)
这是 Go 自动解除引用:
来自https://golang.org/ref/spec#Method_values :
与选择器一样,使用指针对具有值接收器的非接口方法的引用将自动取消对该指针的引用:pt.Mv 相当于 (*pt).Mv。