Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using new vs. { } when initializing a struct in Go

Tags:

go

So i know in go you can initialize a struct two different ways in GO. One of them is using the new keyword which returns a pointer to the struct in memory. Or you can use the { } to make a struct. My question is when is appropriate to use each? Thanks

like image 647
165plo Avatar asked Nov 28 '22 07:11

165plo


2 Answers

Going off of what @Volker said, it's generally preferable to use &A{} for pointers (and this doesn't necessarily have to be zero values: if I have a struct with a single integer in it, I could do &A{1} to initialize the field). Besides being a stylistic concern, the big reason that people normally prefer this syntax is that, unlike new, it doesn't always actually allocate memory in the heap. If the go compiler can be sure that the pointer will never be used outside of the function, it will simply allocate the struct as a local variable, which is much more efficient than calling new.

like image 22
joshlf Avatar answered Dec 23 '22 21:12

joshlf


I prefer {} when the full value of the type is known and new() when the value is going to be populated incrementally.

In the former case, adding a new parameter may involve adding a new field initializer. In the latter it should probably be added to whatever code is composing the value.

Note that the &T{} syntax is only allowed when T is a struct, array, slice or map type.

like image 146
Agis Avatar answered Dec 23 '22 21:12

Agis