0

I'm following the golang tour, this page: https://tour.golang.org/methods/3

package main

import (
    "fmt"
    "math"
)

type Vertex struct {
    X, Y float64
}

func (v Vertex) Scale(f float64) *Vertex {
    v.X = v.X * f
    v.Y = v.Y * f
    return &v //I'm returning a pointer to v
}

func (v Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
    v := &Vertex{3, 4}
    fmt.Printf("Before scaling: %+v, Abs: %v\n", v, v.Abs())
    v = v.Scale(5) //I'm assiging it to v
    fmt.Printf("After scaling: %+v, Abs: %v\n", v, v.Abs())
}

When i call v.Scale a copy of v is passed to the Scale function. Then, the Scale returns a pointer to the v that it has recevied.

Is this safe? Or will i end up with a sigsev at some point?

(Sorry for the title, but i couldn't think of a proper one feel free to edit it)

Federico Ponzi
  • 2,682
  • 4
  • 34
  • 60

1 Answers1

1

That's perfectly safe. When you call v.Scale, a copy of Vertex is allocated and you return a pointer to it. The copy won't be garbage collected as long as it's referenced to by the pointer. If the pointer goes out of scope (and can't be used anymore), the copy would be freed.

Zippo
  • 15,850
  • 10
  • 60
  • 58