Search code examples
pointersgostructnew-operator

What is the core difference between t=&T{} and t=new(T)


It seems that both ways to create a new object pointer with all "0" member values, both returns a pointer:

type T struct{}
...
t1:=&T{}
t2:=new(T)

So what is the core difference between t1 and t2, or is there anything that "new" can do while &T{} cannot, or vice versa?


Solution

  • […] is there anything that "new" can do while &T{} cannot, or vice versa?

    I can think of three differences:

    • The "composite literal" syntax (the T{} part of &T{}) only works for "structs, arrays, slices, and maps" [link], whereas the new function works for any type [link].
    • For a struct or array type, the new function always generates zero values for its elements, whereas the composite literal syntax lets you initialize some of the elements to non-zero values if you like.
    • For a slice or map type, the new function always returns a pointer to nil, whereas the composite literal syntax always returns an initialized slice or map. (For maps this is very significant, because you can't add elements to nil.) Furthermore, the composite literal syntax can even create a non-empty slice or map.

    (The second and third bullet-points are actually two aspects of the same thing — that the new function always creates zero values — but I list them separately because the implications are a bit different for the different types.)