Supoose that I have a Vertex
type
type Vertex struct {
X, Y float64
}
and I've defined a method
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
What's the difference between those two calls ? (both of them return the same result)
v1 := Vertex{3, 4}
fmt.Println(v1.Abs())
v2 := &Vertex{3, 4}
fmt.Println(v2.Abs())
The first version is the equivalent of
var v1 Vertex
v1.X = 3
v1.y = 4
fmt.Println((&v1).Abs)
The second version is the equivalent of
var v2 *Vertex
v2 = new(Vertex)
v2.X = 3
v2.y = 4
fmt.Println(v2.Abs)
So the only substantial difference is that v1
is a value and v2
is a pointer to a value of type Vertex
.