在Go中初始化结构时使用new与{}
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
所以我知道在Go中您可以使用两种不同的方式初始化struct。 其中之一是使用new关键字,该关键字返回指向内存中结构的指针。 或者,您可以使用{}来构建结构。 我的问题是什么时候适合使用每个? 谢谢 p> div>
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.
Most people use A{}
to create a zero value of type A
, &A{}
to create a pointer to a zero value of type A
. Using new
is only necessary for int
and that like as int{}
is a no go.
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.