Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Idiomatic?) Difference between new(T) and &T{...}?

Tags:

go

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?

like image 787
Marcus Riemer Avatar asked Mar 23 '26 10:03

Marcus Riemer


1 Answers

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.

like image 115
Toni Cárdenas Avatar answered Mar 25 '26 01:03

Toni Cárdenas