What is the difference between new and make?

As mentioned in Making slices, maps and channels:

The built-in function make takes a type T, which must be a slice, map or channel type, optionally followed by a type-specific list of expressions.
It returns a value of type T (not *T).
The memory is initialized as described in the section on initial values.

For instance, for Slice type

make([]T, length, capacity)

produces the same slice as allocating an array and slicing it, so these two expressions are equivalent:

make([]int, 50, 100)
new([100]int)[0:50]

So here, make creates the slice, and initialize its content depending on the zero value if the type used (here int, so ‘0‘)

You can see more about the need of keeping new and make separate in Go: why would I make() or new()?


Dave cheney just wrote a good article: “Go has both make and new functions, what gives ?

Although make creates generic slice, map, and channel values, they are still just regular values; make does not return pointer values.

If new was removed in favour make, how would you construct a pointer to an initialised value ?

Using new to construct a pointer to a slice, map, or channel zero value works today and is consistent with the behaviour of new.

For the confusion they may cause, make and new are consistent;

  • make only makes slices, maps, and channels,
  • new only returns pointers to initialised memory.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)