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:
newon 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. Anew(int)that does not escape can stay on the stack.
More on Language Fundamentals & Types
- Q1What are the zero values of Go's types, and which zero values are "usable" versus dangerous?
- Q3What does this program print? (iota)
- Q4What are untyped constants? Explain why
const huge = 1 << 100compiles. - Q5What is the difference between a typed and an untyped constant when you assign or compare it?
- Q6Explain variable shadowing. Find the bug in this code.
- Q7What are the rules for
:=redeclaration, and why does this not compile?