Reputation: 10811
In Go, given struct type T, what is the difference between new(T)
and &T{}
?
Upvotes: 4
Views: 732
Reputation: 8434
Extending @Doug answer:
The two forms new(T)
and &T{}
are completely equivalent: Both allocate a zero T and return a pointer to this allocated memory. The only difference is, that &T{} doesn't work for builtin types like int
; you can only do new(int)
.
Upvotes: 5
Reputation: 10811
There is no difference. According to Effective Go, they are equivalent.
As a limiting case, if a composite literal contains no fields at all, it creates a zero value for the type. The expressions new(File) and &File{} are equivalent.
Upvotes: 9