Go

What is the difference between new and make?

Question 2MediumGo 1.22 to 1.25

new(T) works for any type. It allocates a zeroed T and returns a *T. make only works for slices, maps and channels. It initializes the runtime data structure behind them (the backing array, the hash table, or the channel buffer) and returns the value itself, T, not a pointer.

p := new(int)            // *int pointing to 0
m1 := new(map[string]int) // *map[string]int pointing to a NIL map
(*m1)["a"] = 1            // panic: nil map

m2 := make(map[string]int, 16) // ready to use, room for about 16 entries
s := make([]int, 3, 10)        // len 3, cap 10
ch := make(chan int, 4)        // buffered channel

Gotchas:

  • new on a map, slice or channel gives you a pointer to a nil value. That is almost never what you want.
  • new(T) and &T{} are equivalent for structs. Idiomatic code usually uses the composite literal.
  • Where the value ends up (heap or stack) is decided by escape analysis, not by whether you used new. A new(int) that does not escape can stay on the stack.

More on Language Fundamentals & Types

All 39 Language Fundamentals & Types questions