Pointers and Memory Allocation

How Go allocates memory for pointer values using the new built-in, why pointers to local variables are safe, and how to choose a method receiver

Go gives you direct control over whether you work with a value itself or a pointer to it, but the language also takes on the hard part of deciding where in memory that value lives. This group looks at the mechanics underneath: how you allocate memory for pointer targets, what happens when you point to a local variable, and how method receivers connect allocation decisions to program behavior. Where a value lives is always the compiler's decision, observable with -gcflags="-m", never a promise the language makes.

The new Built-in

The new function allocates memory for a value of a given type, sets every byte of that memory to zero, and returns a pointer to it. Since Go 1.26 it also accepts an expression, so new(42) returns a *int pointing to 42. new never runs constructor logic and never initializes the internal structures of a map, slice, or channel, so use make for those types.

Pointers to Local Variables

In Go, returning the address of a local variable is safe. The compiler performs escape analysis: when a variable's address can be reached after the function returns, the compiler places the variable where it can survive, and the garbage collector manages its lifetime. When the address never leaves the function, the compiler may keep the value on the stack. Either way, you do not need to track stack lifetimes yourself.

Pointer Receivers vs Value Receivers

A method can take a value receiver, which receives a copy of the struct, or a pointer receiver, which receives a pointer to the original and can modify it. A pointer-receiver method is not in the method set of the value type T, so a T value does not satisfy an interface that requires it, even though an addressable T value can call the method directly. As a rule, pick one receiver style for a type and stay consistent.

The new Built-in

How to use new in Go to allocate zeroed memory and obtain a pointer, and how it differs from make

Pointers to Local Variables

How Go safely handles returning pointers to local variables, explained through escape analysis and heap allocation.

Pointer Receivers vs Value Receivers

Learn how to choose between pointer and value receivers in Go methods, understand addressability rules, and avoid common pitfalls.