Apart from the standard way to declare variables, Go offers another way to declare variables via the built-in function new function. Its format is:
Can you guess what's the type for myVar on the example above? If you guessed *myType, you got it right: the new function returns a pointer to the specified type. So let's understand a little more about it.
A deeper look
Because new always returns a pointer to the specified type, it's fair to say that as with pointers, every call to the new function will create an unnamed variable, initialize it its zero value and return its address, a pointer to the specified type. For example:
p: 0xc000100010, *p: 0, &p: 0xc000102018
When to use the new function?
And when should we use new?
The main reason to use new is that you don't need to declare a new variable just to assign values to your pointers, with the tradeoff that your code becomes less readable.
Think of it as a convenience to abbreviate the three-step process of declaring and assigning values to pointers:
Conclusion
On this article we learned about the new function in Go. One of the advantages of using new is that you don't need to declare a dummy variable to assign your pointers to it. But since new returns a pointer to the specified type, it may be confusing for new users of the language. For that reason, the new function is not very used but definitely, it's worth knowing.