Doug Richardson
Doug Richardson

Reputation: 10811

What is the difference between new(T) and &T{}?

In Go, given struct type T, what is the difference between new(T) and &T{}?

Upvotes: 4

Views: 732

Answers (2)

Pravin Mishra
Pravin Mishra

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

Doug Richardson
Doug Richardson

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

Related Questions