What is the conceptual difference between the make and new keywords, and which types can make be used with and why?
Last updated
new(T) allocates zeroed memory and returns a *T, while make initializes and returns a ready-to-use slice, map, or channel (not a pointer): the difference is that those three types need internal setup beyond zeroing.
new(T):Works for any type; allocates and zeroes it, returning a pointer
*T.The zero value is usable for many types but not for maps/channels (a nil map panics on write).
make:Only for
slice,map, andchan; returns an initialized value of typeT, not a pointer.Why these three: they are reference types backed by runtime data structures (slice header, hash table, channel buffer) that must be constructed before use.
Quick mental model:
new= "give me a zeroed pointer";make= "give me a usable built-in collection".
[lang:go]
p := new(int) // *int pointing to 0
m := make(map[string]int) // ready to write
s := make([]int, 0, 10) // len 0, cap 10
ch := make(chan int, 5) // buffered channel