Go: new vs make
Published on

Contents
new and make both allocate memory in Go, but they do different jobs.
new(T)
- Allocates memory for a value of type
Tand sets it to the zero value. - Returns a pointer to it,
*T. - Works with any type.
Example
p := new(int) // p is of type *int
fmt.Println(*p) // 0, the zero value of int
*p = 42
fmt.Println(*p) // 42
Use new when you need a pointer to a zeroed value.
make(T, ...)
- Works only with slices, maps and channels.
- Sets up what they need inside: a slice’s backing array, a map’s hash table, a channel’s buffer.
- Returns the value itself, not a pointer.
Example
s := make([]int, 3) // slice with length 3
fmt.Println(s) // [0 0 0]
s[0] = 10
fmt.Println(s) // [10 0 0]
Use make when you need a slice, map or channel that’s ready to use.
It matters most for maps. A map you only declare is nil, and writing to
it panics:
var m map[string]int
m["a"] = 1 // panic: assignment to entry in nil map
m = make(map[string]int)
m["a"] = 1 // works
Summary
new | make | |
|---|---|---|
| Returns | A pointer, *T | The value, T |
| Works with | Any type | Slices, maps and channels |
| What you get | A zeroed value | A value that’s ready to use |
| Example | new(int) is *int | make([]int, 3) is []int |