Go: new vs make
Published on

Contents
Difference between — new
vs make
in Go can be confusing at first, but
here’s a simple breakdown:
new(T)
- Allocates memory for a value of type
T
- Returns a pointer to zero-initialized value of type
T
- Works for any type
Example
p := new(int) // p is of type *int
fmt.Println(*p) // 0 (default int value)
*p = 42
fmt.Println(*p) // 42
Use new
when you want a pointer to a value of any type.
make(T, ...)
- Creates and initializes built-in reference types:
- slice
- map
- channel
- Returns the value, not a pointer
- Can’t be used with structs or other basic types
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 want to create a slice, map, or channel that’s ready to use.
Summary Table
Feature | new |
make |
---|---|---|
Returns | Pointer | Value |
Usable with | Any type | Only: slice, map, channel |
Zero value | Yes | Initialized, ready to use |
Example type | int , struct |
[]int , map[string]int |