I started kidding around with Go and am a little irritated by the new
function. It seems to be quite limited, especially when considering structures with anonymous fields or inline initialisations. So I read through the spec and stumbled over the following paragraph:
Calling the built-in function new or taking the address of a composite literal allocates storage for a variable at run time.
So I have the suspicion that new(T)
and &T{}
will behave in the exact same way, is that correct? And if that is correct, in what situation should new
be used?
Yes, you are correct. new
is not that useful with structs. But it is with other basic types. new(int)
will get you a pointer to a zero-valued int
, and you can't do &int{}
or similar.
In any case, in my experience, you rarely want that, so new
is rarely used. You can just declare a plain int
and pass around a pointer to it. In fact, doing this is probably better because liberates you from thinking about allocating in the stack vs. in the heap, as the compiler will decide for you.