Golang Memory Allocation: When to Use new() Versus make()
Zero Values and Pointer Basics
When you declare a variable using var, Go automatically assigns a zero value based on the type. For numeric types, this is 0; for strings, it's an empty string ""; and for reference types like slices, maps, and channels, the zero value is nil.
var count int // zero value: 0
var name string // zero value: ""
var data []int // zero value: nil
Consider this problematic code:
package main
import "fmt"
func main() {
var ptr *int
*ptr = 42
fmt.Println(*ptr)
}
Running this produces a panic:
panic: runtime error: invalid memory address or nil pointer dereference
The issue stems from the fact that ptr holds nil—it doesn't point to any allocated memory. The *int declaration only creates a pointer variable, not the integer itself. To actually allocate memory for the pointed-to value, we need either new() or make().
Using new() for Value Types
The new() built-in allocates memory and returns a pointer to a zero-initialized value of the specified type. It works with any allocatable type: structs, arrays, slices, maps, channels, and primitives.
type Config struct {
Port int
Host string
}
func main() {
cfg := new(Config)
fmt.Printf("%+v\n", cfg) // &{Port:0 Host:}
}
Here, cfg is a *Config pointing to a struct with all fields set to their zero values.
For primitive types:
func main() {
num := new(int)
fmt.Println(*num) // 0
flag := new(bool)
fmt.Println(*flag) // false
}
The new() function internally calls runtime.newobject, which allocates a memory block equal to the type's size and initializes it to zero.
To examine the pointer address:
package main
import (
"fmt"
"unsafe"
)
func main() {
ptr := new(int)
addr := uintptr(unsafe.Pointer(ptr))
fmt.Println("Address:", addr)
}
This demonstrates that new(int) creates space for an integer and returns its memory address as a pointer.
Using make() for Reference Types
The make() function initializes and returns the actual value (not a pointer) for slices, maps, and channels. Unlike new(), make() cannot be used with arbitrary types—it specifically targets these three reference types.
func main() {
// slice: length 0, capacity 10
numbers := make([]int, 0, 10)
// map: with optional initial capacity
lookup := make(map[string]int, 100)
// channel: unbuffered by default
messages := make(chan int)
fmt.Println(numbers, lookup, messages)
}
Creating a slice with pre-allocated elements:
func main() {
data := make([]int, 5)
fmt.Println(data) // [0 0 0 0 0]
}
The make() function uses different runtime implementations: runtime.makeslice for slices, runtime.makemap for maps, and runtime.makechan for channels.
Inspecting slice internals:
package main
import (
"fmt"
"reflect"
"unsafe"
)
func main() {
s := make([]string, 4)
val := reflect.ValueOf(s)
baseAddr := val.Elem().UnsafeAddr()
length := val.Len()
fmt.Printf("Base: %d, Length: %d\n", baseAddr, length)
}
Fixing the Nil Pointer Issue
Returning to our original problem, we can resolve the panic by allocating memory:
func main() {
var ptr *int
ptr = new(int)
*ptr = 42
fmt.Println(*ptr) // 42
}
This works because new(int) allocates memory for an integer, and ptr now points to valid memory.
Key Differences Summary
| Aspect | new(T) |
make(T, args...) |
|---|---|---|
| Return type | *T (pointer) |
T (value) |
| Applicable types | All allocatable types | Slices, maps, channels only |
| Initial state | Zero values | Type-specific initialization |
| Memory location | Heap | Heap |
new() allocates memory and zeros it, returning a pointer. make() creates and initializes slice/map/channel instances with proper internal structures.
In practice, new() sees limited use because idiomatic Go favors short variable declarations and struct literals. However, make() is essential—without it, operations on slices, maps, and cahnnels would panic due to nil references.