I am currently learning to program with Go language. I am having some difficulties understanding Go pointers (and my C/C++ is far away now...). In the Tour of Go #52 (http:/
There are two different rules of the Go language used by your examples:
It is possible to derive a method with a pointer receiver from a method with a value receiver. Thus func (v Vertex) Abs() float64
will automatically generate an additional method implementation:
func (v Vertex) Abs() float64 { return math.Sqrt(v.X*v.X+v.Y*v.Y) }
func (v *Vertex) Abs() float64 { return Vertex.Abs(*v) } // GENERATED METHOD
The compiler will automatically find the generated method:
v := &Vertex{3, 4}
v.Abs() // calls the generated method
Go can automatically take the address of a variable. In the following example:
func (v *Vertex) Abs() float64 { return math.Sqrt(v.X*v.X+v.Y*v.Y) }
func main() {
v := Vertex{3, 4}
v.Abs()
}
the expression v.Abs()
is equivalent to the following code:
vp := &v
vp.Abs()