9

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

0

3 Answers 3

14

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1, but It may be worth clarifying that SomeType{} will initialize a value whereas new(SomeType) or &SomeType{} will initialize a pointer... Also worth noting--you don't need to know every value for every field to use {}--you can initialize 0 fields, all fields, or anything in between. I only use new() when I don't want to initialize anything at allocation time, and even then I often just use &SomeType{}
9

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.

Comments

8

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 newis only necessary for int and that like as int{} is a no go.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.