I found make and new very interesting and hence decided to list down the differences:
new ---> returns pointer
make ---> returns an initialized value of type Tnew ---> initializes to 0 value of the type
make ---> does not initialize to 0 value of the typenew ---> used for all types
make ---> used for only slices, maps and channels
Top comments (3)
In what circumstance would you use
new(StructType)
over something like&StructType{}
? I tend to use the latter everywhere as it's easier later to add fields.Even I use
&StructType{}
most of the times. During initialization if the values of the fields are not known,new(StructType)
is good to use as it initialises them to zero values of the fields.Iโve attempted to use
new(StructType)
for the last 2 days and Iโve found that it does make intention easier to read when skimming through code. It especially helps when unmarshaling json/protobuf into a struct as I quite often miss out the&
to create a pointer in my haste and wonder why it doesnโt work later!new
eliminates this as it is always a pointer! ๐