DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Anusha Bhat
Anusha Bhat

Posted on

3 difference between make and new in Go

I found make and new very interesting and hence decided to list down the differences:

  1. new ---> returns pointer
    make ---> returns an initialized value of type T

  2. new ---> initializes to 0 value of the type
    make ---> does not initialize to 0 value of the type

  3. new ---> used for all types
    make ---> used for only slices, maps and channels

Top comments (3)

Collapse
 
ndane profile image
Nathan Dane

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.

Collapse
 
anusha_bhat profile image
Anusha Bhat

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.

Collapse
 
ndane profile image
Nathan Dane

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! πŸ˜‹

Layoffs: It’s Okay to Not Be Okay