Pointer Fundamentals

Learn what pointers are in Go, how to declare and use them, the & and * operators, and how to work with pointers to structs

Every variable you create in a Go program lives somewhere in memory. A pointer is a variable that stores that somewhere, the memory address of another variable. Instead of holding a number or a string directly, it holds a location you can follow to find the actual data.

Pointers matter because not all data is small and cheap to copy. When you pass a large struct to a function without a pointer, Go duplicates the entire thing, and if the function needs to change the original, that duplicate is useless. Pointers let you share data without copying it and let you modify it in place. This group covers the three building blocks: the pointer type itself, the operators that work with memory addresses, and pointers to structs.

Pointer Types and Declaration

A pointer type is written by placing a * in front of the type it points to: *int points to an integer, *string points to a string. The zero value of any pointer type is nil, a pointer that holds no address. You create a pointer with the address operator, as in p := &x, or with the built-in new, as in p := new(int). Every pointer type is tied to its base type, so a *int cannot hold the address of a string.

Address and Dereference Operators

The & operator produces the memory address of a variable, and the * operator follows a pointer back to the value at that address. Reading through a pointer gives you the original value, and writing through it changes the original variable. You can only take the address of something that has a fixed location in memory, and you can only dereference a pointer that is not nil, dereferencing a nil pointer panics at runtime. Go has no pointer arithmetic.

Pointers to Structs

A pointer to a struct lets functions and methods work on the original struct without copying it. You create one with &alice, with new(Person), or with the composite literal form &Person{Name: "Bob", Age: 25}. Go automatically dereferences the pointer when you access a field, so p.Name means (*p).Name, and writing through the pointer changes the original struct. A nil struct pointer panics on any field access, so always initialize it first.

Pointer Types and Declaration

How to declare pointer variables in Go, understanding the *T syntax, zero value nil, and type safety rules

Address and Dereference Operators

Learn how the address operator (&) and dereference operator (*) work in Go, with practical examples and common pitfalls.

Pointers to Structs

How to create and work with pointers to structs in Go, including automatic field dereferencing, modification, and common pitfalls.