liveBook · Manning

Pointer

As explained in Go in Action, Second Edition

A pointer type is a Go type whose values identify the memory locations of values of a specified target type.

Go normally copies a value when assigning it to another variable or passing it to a function. A pointer instead holds the memory address of a value of a specified type. It lets code share and, when appropriate, modify that value without copying the value itself. This is useful for large arrays and structs, and for methods that update receiver state. section 5.3 section 5.7

The type *int means “pointer to an int.” Use & to obtain a value’s address and * to dereference a pointer—to read or change the value at that address. A declared pointer’s zero value is nil, meaning it does not yet point to a value. section 3.7 section 3.7.1

Change a value through its pointer

count := 0 ptr := &count // ptr has type *int *ptr = 1 // count is now 1 Printing ptr shows its address; printing *ptr shows the int stored there. Assignment through *ptr changes the original value, not a separate copy. section 3.7 section 3.7.1

Pass an image array without copying it

type image4K [3840 * 2160]int func processPixels(pixels *image4K) { // Process the original array through pixels. } func main() { var pixels image4K processPixels(&pixels) } Go still passes the argument by value: the copied value is the pointer, not the entire array. Changes made to array elements through that pointer affect the original array. section 4.1.7

For a new struct, &person{name: "Andy", age: 42} creates a pointer while initializing its fields; new(person) creates a pointer to a zero-valued person. Use new(int) when a pointer to a new built-in value is needed. Choose a pointer when sharing, modification, or avoiding a substantial copy matters; otherwise, ordinary value copying keeps changes independent. section 3.7.2 section 5.3

How Go in Action, Second Edition covers it

How deep it goes
Explains typed pointers, nil, addressing, dereferencing, and construction, then applies them to function arguments without descending into memory management internals.
Examples
Uses an integer changed through dereferencing, struct initialization, and a large image array passed to a function.
What it assumes
Assumes familiarity with Go variables and functions while teaching pointer declarations, address-taking, and dereferencing directly.
What you can do after
Apply pointers in Go to modify original values and pass large arrays without copying their contents.
How it connects
Connects pointers to copy by value, arrays, structs, methods, slices, and maps.

Also explained in

Compare how 2 books explain pointer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.