This question already has an answer here:
I am going through the Tour of Go again, and I am confused by this Methods Module
In short a type Vertex
is specified as well as a function with a pointer receiver
type Vertex struct {
X, Y float64
}
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
No worries here. However, my confusion comes from the main function which appears to allow a value type to invoke a method which specifies a pointer receiver.
func main() {
v := Vertex{3, 4}
v.Scale(10)
// v's fields have changed
}
I checked the type of v just to make sure
fmt.Printf("v's type is %T
", v)
// v's type is main.Vertex
Why is this allowed? Shouldn't v
need to be a pointer to invoke the Scale
method e.g. v := &Vertex{3, 4}
</div>