Golang - Doubt about pointers

Asked

Viewed 410 times

4

I have a struct called Calculator, with two properties: version and author. To be able to instantiate this struct already initiating these methods, since Golang has no constructors, the various tips I found on the net indicate to create a Newcalculator() method and then use it to instantiate the calculator. The method would look like this:

func NewCalculadora() *Calculadora {
        return &Calculadora{autor:"Paulo Luvisoto",versao:1.0}
}

And all tips indicate the use of pointer, as above. But I saw that so also works:

func NewCalculadora() Calculadora {
        return Calculadora{autor:"Paulo Luvisoto",versao:1.0}
}

My question is: what is the problem of using this second way, without using pointer?

  • Golang will "convert" internally if you use func (c *Calculadora) ..., then use & would be preferable. That is, as far as I know.

1 answer

5


The best definition I’ve ever heard on this subject was this::

Pointers are for sharing.

Usually this doubt comes down to a question of semantics.

For example: You create a value of type Calculadora.

calc := NewCalculadora()

Okay, you’ve got your calculator (Calc).

Do you intend/need to change/change the values of this type? (author or version)

No? Then returning a copy is enough. Remember that in Go arguments are passed by value (copy).

In your case, if you want to change any of the fields of this type, you need a pointer.

A beautiful example of this is the package time.

See the function Time.Add, although you add a duration to an instant of time, you are not changing that "instance", but are returning a new value.

Going against the grain, the package os, has the type os. File which uses pointer semantics. Since in this case it is much more logical for you to share a file than to create copies.

So, there is no problem in using with or without pointer, everything will depend on what you intend to do. I hope this helps resolve your doubt.

  • Navossoc, I think it’s starting to clear up. For example... if I have a struct with two properties and I want to do getters and setters for these two properties, in the case of getters I don’t need pointers. But in the case of setters, yes, because I will be changing the properties. Proceed?

  • That’s basically what you said, except for the reference types that wouldn’t necessarily need a pointer to be modified, but still, you need to be extra careful when manipulating them. If you really want to use real language, you will need to give a good study to avoid unpleasant surprises in the future (I’m still learning too).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.