Calling a method with a pointer receiver object instead of a pointer to it?

vis an object Vertex, and Scaleis a method for a pointer to Vertex. Then why is it v.Scale(10)not mistaken, considering that vit is not a pointer to an object Vertex? Thank.

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())
}
+4
source share
2 answers

Spec: Calls:

x.m() , () x m, m. x &x m, x.m() (&x).m().

, Scale() , , v ( ), v.Scale(10) (&v).Scale(10).

, , .

+8
+2

Source: https://habr.com/ru/post/1648505/


All Articles