Golang - Doubt over pointers

4

I have a struct called Calculator, with two properties: version and author. In order to instantiate this struct already initializing these methods, since Golang does not have constructors, the various tips that I found in the net indicate to create a NewCalculadora () method and later to use it to instanciar the Calculator. The method would look like this:

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

And all the pointers indicate the use of pointer, as above. But I have seen that this also works:

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

My question is: what's the problem with using this second way, without using a pointer?

    
asked by anonymous 04.11.2017 / 01:02

1 answer

4

The best definition I've heard about this subject is this:

  

Pointers are for sharing.

This question usually comes down to a matter of semantics.

For example: You create a value of type Calculadora .

calc := NewCalculadora()

Ok, you have your calculator (calc).

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

No? So returning a copy is enough. Remember that in Go the 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 good example of this is the time package.

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

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

So, there's no problem in using it with or without a pointer, it all depends on what you intend to do. I hope this helps resolve your question.

    
08.11.2017 / 15:41